Hena has asked for the wisdom of the Perl Monks concerning the following question:

Hello monks, I've encountered a odd behaviuor in last, that I don't understand. It feels like a bug, but is it a feature i don't know. So I present the question here :). I have a test program.
#!/usr/bin/perl # # testing last # use strict; use warnings; my $i=0; my $file="test.file"; foreach my $count (1 .. 10) { open (INF,"$file") or die "Unable to open '$file': $!"; $i++ && m/2/ && last while (<INF>); close INF; $i=0; print "here:$count\n" } print "END($i)\n"; exit;
And data-file for it.
1
2
3
4
Now when running the program ($i is line-count). Last actually ends the foreach loop, even though it should (at least I think so) end the while loop. However, if the while loops line is changed to this.
m/2/ && $i++ && last while (<INF>);
It prints correct output. So is this how it should work? My version of perl is 5.8.0 for RedHat 9.0.

Replies are listed 'Best First'.
Re: Last oddity
by PodMaster (Abbot) on Oct 21, 2004 at 09:08 UTC
    `perldoc -f last'
    ...If the LABEL is omitted, the command refers to the innermost enclosing loop.
    What you have there is not an enclosing loop, its a statement modifier (see `perldoc perlsyn' for details).

    MJD says "you can't just make shit up and expect the computer to know what you mean, retardo!"
    I run a Win32 PPM repository for perl 5.6.x and 5.8.x -- I take requests (README).
    ** The third rule of perl club is a statement of fact: pod is sexy.

      Ok, so assumption that while { something } and something while; are identical things is wrong. That clear up a lot.
Re: Last oddity
by Anonymous Monk on Oct 21, 2004 at 09:13 UTC
    The last should end the for loop, as an EXPR1 while EXPR2 doesn't create a block for EXPR1, and last exits a block.

    The difference between your two statements is that in the first one, you actually reach the last. But m/2/ && $i++ is never true. m/2/ is true only once, but then $i is still 0. Just add a 12 to your data file and notice the difference. In the expression $i++ && m/2/, $i is incremented each time, not only when there's a 2 in the input, making all the difference in the world.

      Ups, should've been doing ++$i :D. Thanks for pointing out.