Bug#843803: Please catch illegal use of $F[0..1] as syntax error

Niko Tyni ntyni at debian.org
Wed Nov 9 21:56:09 UTC 2016


On Thu, Nov 10, 2016 at 02:43:28AM +0800, 積丹尼 Dan Jacobson wrote:
> Package: perl
> Version: 5.24.1~rc3-3
> Severity: wishlist
> 
> Please catch illegal use of $F[0..1] as syntax error.
> 
> Else it gets interference from "$."!

It's not illegal: the index is evaluated in scalar context and the
$. "interference" you mention is documented behaviour. See perlop,
"Range Operators".

In scalar context, '..' acts as a "flip-flop" operator, and constant
operands are compared to the current line number ("$."). This enables
things like "perl -ne 'print if 2..5' /etc/passwd".

See also http://www.perlmonks.org/?node_id=525392

> use strict;
> use warnings FATAL => q(all);
> $_=`ps -axo pid=`;
> my $c;
> for(split){
>     last if ++$c > 5;
>     open N, "/proc/$_/stat" or next;
>     my @F = split " ", <N>;
>     close N;
>     print  "@F[0..$c]\n=>$F[0..1]\n\n";
> }

Here $. is always 0, so the left operand of 0..1 is true and the
resulting index increments on every evaluation.

> my @A=(7..99);
> print $A[0..1],"\n";
> print $A[0..2],"\n";
> print $A[1..2],"\n";

$. is still 0 so we get 1 for the first two indices and the empty string
(false) for the last one.

> Tell the user
> die "Did you mean @F[0..1]?"

No, it's perfectly legal. At most warn.
-- 
Niko Tyni   ntyni at debian.org




More information about the Perl-maintainers mailing list