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 ) {
...
...
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With