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 ) {
...
...
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, in the first example, the
forloop 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 theforloop.$_has dynamic scope, and will be visible in any functions called from within theforloop. You should primarily use this version of theforloop when you plan on using$_for its special features.Also, in the first example,
$scalaris a copy of the value in the array, whereas in the second example,$scalaris 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.