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

Time:08-05

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? Thanks much in advance!

CodePudding user response:

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.

CodePudding user response:

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 array, and the external, pre-defined one is left untouched. perl knows the difference.

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

  • Related