[ABE.pm] 'for' statement Q

Ricardo SIGNES perl.abe at rjbs.manxome.org
Fri Aug 15 11:15:33 PDT 2008


* "Faber J. Fedor" <faber at linuxnj.com> [2008-08-15T13:56:16]
> Interesting.  That means I can have an incrementor and a test condition
> in my foreachs! I'm going to have to play with that...

Sure... because foreach and for are the same.

>     $_ = "foobar";
>     
>     my @array = (1,2,3,4,5);
>     
>     foreach (@array) {
>         print;           # prints 1,2,3,4, and 5
>     }
>     
>     print;               # prints 'foobar'
>     
>     foreach (@array, my $i = 0; $i<3; $i++) {
>         print;           # prints foobar three times?!
>     }

I'm not sure what you would've expected.

for expects to be in one of three forms:

  for (EXPR; EXPR; EXPR) BLOCK

  for VAR (LIST) BLOCK
  for (LIST) BLOCK

In the third form, you said:

  for (@array) { print }

which is equivalent to:

  for $_ (@array) { print }

and using $_ as the loop variable localizes it.  In your code:

  foreach (@array) {
    print;           # prints 1,2,3,4, and 5
  }

...$_ is set to each element of @array in turn, then printed.

In your code:

  foreach (@array, my $i = 0; $i<3; $i++) {
    print;           # prints foobar three times?!
  }

You're not writing a "for (LIST)" loop, but a "for (EXPR; EXPR; EXPR)" loop.
In those, you do this:

  10 evaluate first expression
  20 evaluate the second expression; abort loop if false
  30 execute block
  40 evaluate third expression
  50 GOTO 10

Here, your first expression is "@array, my $i = 0" which is ugly, but totally
valid.  It gets evaluated once.

Since you're writing a three-part loop instead of a LIST loop, there is no
assignment to or localization of $_.  $_ keeps its value from outside the loop,
'foobar' while the loop executes three times.

-- 
rjbs


More information about the ABE-pm mailing list