[kw-pm] $1 matching question

Daniel R. Allen da at coder.com
Wed Jul 21 17:11:39 CDT 2004


Er, since $1 is lexically scoped, I'd expect it to follow the same
behaviour as:

perl -e 'foreach (1..5) { my $foo; $foo++; print $foo;}'

since $1 doesn't exist outside the loop.  But I guess it does, since it
has the behaviour it does...

The odd part of all of this is:
The deparsed code for the command-line switch -n:

LINE: while (defined($_ = <ARGV>)) {
    /(\d+)/;
    print "$1 ";
}

differs from the deparsed code for the command-line switch -p:

LINE: while (defined($_ = <ARGV>)) {
    /(\d+)/;
    print "$1 ";
}

continue {
    print $_;
}

by a "continue" block.  When I run the same code but comment out the print
inside the continue block, I get the answer I expected in the first place:

$ cat testperl.pl
LINE: while (defined($_ = <ARGV>)) {
    /(\d+)/;
    print "$1 ";
}

$ echo -e "9 \n \n 2"| perl testperl.pl
9  2


*sigh*

-Daniel



On Wed, 21 Jul 2004 Greg.Fenton at sybase.com wrote:

> But it doesn't go out of scope...it's all inside of the WHILE loop.
>
> greg.fenton
> ----
> Greg Fenton
> Consultant, Solution Services
> iAnywhere Solutions
>
>
>
>
> "Daniel R. Allen" <da at coder.com>
> Sent by: kw-pm-bounces at mail.pm.org
> 07/21/2004 04:32 PM
>
>         To:     kw-pm at mail.pm.org
>         cc:
>         Subject:        Re: [kw-pm] $1 matching question
>
>
>
>
> Ah, thanks, that's the ideom I'd used before- if (/whatever/) { print }
>
> The camel book chapter 2 says:
> "the variables $1, $2, $3 ... are automatically localized, and their scope
> extend to the end of the enclosing block... or to the next successful
> pattern match, whichever comes first".
>
> I guess I'm surprised that $1 didn't go out of scope the next time around
> the WHILE loop (in the deparsed version); that would be the behaviour of
> least surprise, as far as I can tell.
>
> *shrug*
>
> -Daniel
>




More information about the kw-pm mailing list