Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

grep vs for loop

Status
Not open for further replies.

loosecannon1

Programmer
Feb 19, 2002
55
0
0
US
Ok this one's really got me twisted up. I'm trying to set the value of a hash to another hash if two values are the same.

It works with the following for loop:

for(@{$IOprocedures{all}{active}}) {
if ($IOprocedures{current}{number} eq $_->{number}) {
$IOprocedures{current}{active} = $_;
print "[$IOprocedures{current}{active}{number}]\n";
}
}


But not with using the grep function. WHY? WHY? WHY? I receive an error: "Can't use string ("1") as a HASH ref while "strict refs" in use at generateIO.pl line 164." when using the following code:

$IOprocedures{current}{active} =
grep { $IOprocedures{current}{number} eq $_->{number} }
@{$IOprocedures{all}{active}};
print "[$IOprocedures{current}{active}{number}]\n";


My deadline is fast approaching so I'll use for loop, for now. I'm really at a loss on this.
 
A few things to note, the print is not in a loop in your second example and it is in the former. From the sound of it, there's only one record matching anyway, so it probably doesn't matter.

The big deal is grep returns a list of elements where the block evaluated true when it's called in list context. Since you're saving to a scalar, you're enforcing scalar context, where grep returns the number of times the block evaluated true. Try surrounding what grep assigns to in (parentheses) to force list context on the single contained scalar.

Yell if this isn't making much sense, I'm feeling somewhat tounge twisted right now. And read a little on grep's perldoc:
________________________________________
Andrew - Perl Monkey
 
Thank you for the response... you're suggestion worked.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top