Question about the meaning of foreach

I found in the for-loop module written like this:

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

Is there any difference between this and the following way of writing a for loop?

 for my $scalar ( @array ) { ... ... } 
+6
foreach perl
source share
3 answers

Yes, in the first example, the for loop acts as a localizer (setting $_ , which is the default argument for many Perl functions) over the elements in the array. This has the side effect of masking the value of $_ , which is outside the for loop. $_ has a dynamic scope and will be displayed in any functions called inside the for loop. You should use this version of the for loop first when you plan to use $_ for your special functions.

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

And finally, the first example will be a bit slower.

+11
source share

$_ is the "default input and template input field". In other words, if you read from the file descriptor at the top of the while loop or run the foreach loop and do not name the loop variable, $_ configured for you.

However, if you write a foreach loop and name the loop variable, $ _ is not configured. This may be justified by the following code:

 1. #!/usr/bin/perl -w 2. @array = (1,2,3); 3. foreach my $elmnt (@array) 4. { 5. print "$_ "; 6. } 

Output "Using uninitialized value in concatenation (.)"

However, if you replace line 3 with:

 foreach (@array) 

The output is "1 2 3" as expected.

Now in your case it is always better to specify the loop variable in the foreach loop to make the code more readable (perl is already cursed to be less readable), thus, there will also be no need for an explicit assignment to the $_ variable and the resulting determination problems.

+3
source share

I can't explain better than the doc can

+2
source share

All Articles