Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does foreach(@array, $var) work in Perl?

I am trying to figure out some Perl code someone else wrote, and I'm confused with the following syntax of foreach loop

foreach (@array, $var){
 ....
}

This code runs, but nobody else uses it based on my google search online. And it doesn't work the same way as the more common way of foreach with arrays, which is:

foreach $var (@array){
 ....
}

Could someone explain this syntax?

like image 299
Corey C Avatar asked Mar 03 '26 18:03

Corey C


2 Answers

foreach (@array, $var){ .... }

is short for

foreach $_ (@array, $var){ .... }

which is short for

foreach $_ ($array[0], $array[1], ... $array[N], $var){ .... }

So on each iteration of the loop, $_ is set to be each element of the array and then finally to be $var. The $_ variable is just a normal perl variable, but one which is used in many places within the Perl syntax as a default variable to use if one is not explicitly mentioned.

like image 121
Dave Mitchell Avatar answered Mar 05 '26 13:03

Dave Mitchell


Perl's for() doesn't operate on an array, it operates on a list.

for (@array, $var) {...} 

...expands @array and $var into a single list of individual scalar elements, and then iterates over that list one element at a time.

It's no different than if you had of done:

my @array = (1, 2, 3);
my $var = 4;

push @array, $var;

for (@array) {...}

Also, for my $var (@array, $var) {...} will work just fine, because with my, you're localizing a new $var scalar, and the external, pre-defined one is left untouched. perl knows the difference.

You should always use strict;, and declare your variables with my.

like image 35
stevieb Avatar answered Mar 05 '26 12:03

stevieb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!