Reputation: 1907
I need to edit some Perl script and I'm new to this language. I encountered the following statement:
print for (@$result);
I know that $result is a reference to an array and @$result returns the whole array. But what does print for mean?
Thank you in advance.
Upvotes: 0
Views: 765
Reputation: 53478
In Perl, there's such a thing as an implicit variable. You may have seen it already as $_
. There's a lot of built in functions in perl that will work on $_
by default.
$_
is set in a variety of places, such as loops. So you can do:
while ( <$filehandle> ) {
chomp;
tr/A-Z/a-z/;
s/oldword/newword/;
print;
}
Each of these lines is using $_
and modifying it as it goes. Your for
loop is doing the same - each iteration of the loop sets $_
to the current value and print
is then doing that by default.
I would point out though - whilst useful and clever, it's also a really good way to make confusing and inscrutable code. In nested loops, for example, it can be quite unclear what's actually going on with $_
.
So I'd typically:
avoid writing it explicitly - if you need to do that, you should consider actually naming your variable properly.
only use it in places where it makes it clearer what's going on. As a rule of thumb - if you use it more than twice, you should probably use a named variable instead.
I find it particularly useful if iterating on a file handle. E.g.:
while ( <$filehandle> ) {
next unless m/keyword/; #skips any line without 'keyword' in it.
my ( $wiggle, $wobble, $fronk ) = split ( /:/ ); #split $_ into 3 variables on ':'
print $wobble, "\n";
}
It would be redundant to assign a variable name to capture a line from <$filehandle>
, only to immediately discard it - thus instead we use split
which by default uses $_
to extract 3 values.
If it's hard to figure out what's going on, then one of the more useful ways is to use perl -MO=Deparse
which'll re-print the 'parsed' version of the script. So in the example you give:
foreach $_ (@$result) {
print $_;
}
Upvotes: 5
Reputation:
It is equivalent to for (@$result) { print; }
, which is equivalent to for (@$result) { print $_; }
. $_
refers to the current element.
Upvotes: 4