reduce { print wantarray ? "array\n" : defined wantarray ? "scalar\n" : "void\n" } 1 .. 2; # prints "void"
So the eval must optimize itself based on the context, but a normal non-eval'ed block ending with $a + $b would not optimize away, and (I think) still perform and return the addition, even though being in void context.

Certainly I agree that you are right, that this must be a bug in List::Util. The block should be in scalar context since the return value is the important part of this operation. I really wonder how the module can get the return value of something that it executes in void context??

Also, I got some strange behavoir when I add a return statement to the eval. Both should behave the same way, but don't. Why on earth $a gets set to 4 for every addition is a mystery...

my $result = reduce { print "eval: $a + $b\n"; eval "$a + $b" } 1 .. 4; print "result=$result\n\n"; # eval: 1 + 2 # eval: + 3 # eval: + 4 # result=4 $result = reduce { print "eval: return $a + $b\n"; eval "return $a + $b" } 1 .. 4; print "result=$result\n\n"; # eval: return 1 + 2 # eval: return 4 + 3 # eval: return 4 + 4 # result=4
Update: sgifford claims to see scalar context from the block in his reply above -- running his code, I still get void context reported.. This is with Perl 5.8, and List::Util 1.07_00. But even in scalar context, he still gets the weird behavoir? The wonders never cease!

blokhead


In reply to Re: Re: Re: An anomaly with List::Util::reduce and/or eval? by blokhead
in thread An anomaly with List::Util::reduce and/or eval? by BrowserUk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.