Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about the foreach-value

Tags:

foreach

perl

I've found in a Module a for-loop written like this

for( @array ) {
    my $scalar = $_;
    ...
    ...
}

Is there Difference between this and the following way of writing a for-loop?

for my $scalar ( @array ) {
    ...
    ...
}
like image 862
sid_com Avatar asked Mar 11 '10 06:03

sid_com


1 Answers

Yes, in the first example, the for loop is acting as a topicalizer (setting $_ which is the default argument to many Perl functions) over the elements in the array. This has the side effect of masking the value $_ had outside the for loop. $_ has dynamic scope, and will be visible in any functions called from within the for loop. You should primarily use this version of the for loop when you plan on using $_ for its special features.

Also, in the first example, $scalar is a copy of the value in the array, whereas in the second example, $scalar is an alias to the value in the array. This matters if you plan on setting the array's value inside the loop. Or, as daotoad helpfully points out, the first form is useful when you need a copy of the array element to work on, such as with destructive function calls (chomp, s///, tr/// ...).

And finally, the first example will be marginally slower.

like image 97
Eric Strom Avatar answered Oct 13 '22 02:10

Eric Strom