Dear monks,

Some of you already know the golf way to add up a column of numbers.

perl -nle '$t+=$_}{print$t'

This works because perlrun promises the -n option translates the code to

LINE: while(<>) { perl -nle '$t+=$_}{print$t }
so the print statements go to a separate block after the while loop.

(There's actually some tricks how this can be golfed even more, but those are irrelevant for my question so best not to show here.)

So now I tried to do something like that and typed

perl -wnE '$s+=$_}{say$s'

It failed. The error message is

Can't call method "say" without a package or object reference at -e li +ne 1, <> line 2.

When instead I typed

perl -wnE '$s+=$_;END{say$s}'
that works as expected.

It's not hard to guess what happens here: -E enables new features only in the first block, not in the second. This seems contrary to perlrun which says:

-E commandline
behaves just like -e, except that it implicitly enables all optional features (in the main compilation unit). See feature.
The say in the source code is clearly part of the main compilation block, it's not just required from another file.

Modeparse confirms my suspicion:

$ perl -MO=Deparse -wnE '$s+=$_}{say$s'
BEGIN { $^W = 1; } LINE: while (defined($_ = <ARGV>)) { BEGIN { $^H{'feature_say'} = q(1); $^H{'feature_state'} = q(1); $^H{'feature_switch'} = q(1); } $s += $_; } { $s->say; } -e syntax OK $

So my question is, is this a bug or a feature or a documentation bug?

Update 2010-07-08: it seems that this is fixed in perl 5.10.1.


In reply to Interaction of -n}{ and -E: bug or feature? by ambrus

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.