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

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.

Replies are listed 'Best First'.
Re: Interaction of -n}{ and -E: bug or feature?
by kyle (Abbot) on May 30, 2008 at 16:56 UTC

    I might call it a documentation bug, but I think that making the documentation correct could also make it a lot more confusing. I've always used an END block for that kind of usage anyway, so the golf way you show initially looks wrong to me at the outset. If that did not continue to work, I'd shed no tear.