in reply to Re: Differentiating STDIN from arguments when using -n ?
in thread Differentiating STDIN from arguments when using -n ?

I tried this but somehow $x seems to become undef after the first time through the implicit loop.

$ cat gibberish This is a couple of lines of crud $ cat gibberish | perl -Mstrict -Mwarnings -ne ' > my $x; > BEGIN {$x = shift @ARGV; print qq{BEGIN - $x\n}} > print qq{x = $x\n$_};' myarg BEGIN - myarg x = myarg This is a couple Use of uninitialized value in concatenation (.) or string at -e line 4 +, <> line 2. x = of lines of crud $

I wonder what is causing this.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^3: Differentiating STDIN from arguments when using -n ?
by bart (Canon) on Sep 15, 2007 at 11:53 UTC
    Don't declare the $x — it's just a one-liner. Perl wraps a while(<>) { ... } loop around the code you put there (really!), so it's a new $x for every line in the file.

    See for yourself:

    perl -n -MO=Deparse -e 'my $x' foo
    produces:
    LINE: while (defined($_ = <ARGV>)) { my $x; } -e syntax OK