in reply to Short-circuiting a map list.

If you look at the output below, the while loop is entered ('a') just one at the top.

The map is entered ('b') just 6 times as required.

If you look at the bottom, of the output, 'just' the required values are returned.

There is just the minor irritation of the weirdness marked '#??'.

sub a{ my $x = shift; while(1){ print 'a'; map { print 'b'; last if $_ == $x; $_; } @_; print 'c'; }; } my @data = 0 .. 9; print for a( 5, @data ); __END__ c:\test>junk a b b b b b b 0 ##?? 1 ##?? 2 ##?? 3 ##?? 4 ##?? 5 ##?? 6 ##?? 7 ##?? 8 ##?? 9 ##?? 0 1 2 3 4

I guess I was hoping for some of the legendary PM inventiveness?


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

Replies are listed 'Best First'.
Re^2: Short-circuiting a map list. (This works! But ...)
by Anonymous Monk on Oct 08, 2011 at 15:13 UTC

    In 5.12.2 I get as you, 0,1,2,3,4,5,6,7,8,9, with 0,1,2,3,4

    If I explicitly add return map{} I get only 0,1,2,3,4,5,6,7,8,9, without 0,1,2,3,4

    In perl 5.6 I get 0,1,2,3,4,5,6,7,8,9, without 0,1,2,3,4

    In perl 5.14.1 I get 0,1,2,3,4,5,6,7,8,9, BUT with 0,0,0,0

    perlsub says: If no return is found and if the last statement is an expression, its value is returned. If the last statement is a loop control structure like a foreach or a while , the returned value is unspecified.

      Okay. If what you are telling me is that I am utilising unspecified behaviour, then how about this version which produces identical output but, as far as I can tell, does nothing that is either prohibited or unspecified?

      sub a{ my $x = shift; return do{ { print 'a'; map { print 'b'; last if $_ == $x; $_; } @_; print 'c'; } }; } my @data = 0 .. 9; print for a( 5, @data );

      Does that mean uncovered an obscure bug?


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.

        Does that mean uncovered an obscure bug?

        Probability is high :)

        do does say "do BLOCK" does *not* count as a loop, so the loop control statements "next", "last", or "redo" cannot be used to leave or restart the block. See perlsyn for alternative strategies.

        The behaviour is just as unspecified for a bare loop ({ ... }) as it is for a while loop (while (...) { ... }).