http://www.perlmonks.org?node_id=759648


in reply to my $1

Why do $1 and $2 behave differently than $_

Do they?

$ perl -e 'my $_ = 1' Can't use global $_ in "my" at -e line 1, near "my $_ "

Hint: use local for global/package variables instead (if you really need to...).

Or, in your case with $1 etc., I think simply creating a local copy of $1 with my $capt1 = $1; would be sufficient for your recursion problem.

Replies are listed 'Best First'.
Re^2: my $1
by grinder (Bishop) on Apr 23, 2009 at 20:34 UTC
    perl -e 'my $_ = 1' Can't use global $_ in "my" at -e line 1, near "my $_ "

    That's just your copy of perl, which is too old :) Works fine in 5.10.

    • another intruder with the mooring in the heart of the Perl

      Baah, this gives me creeps.
      perl -e '@foo = map {$_=2; foo()} 1..10; sub foo{print}' 2222222222 $ perl -e '@foo = map {my $_=2; foo()} 1..10; sub foo{print}' 12345678910

      print "just another perl5.8 hacker"
        Baah, this gives me creeps.
        Does this give you also the creeps?
        $ perl -e 'for $x (1 .. 9) {$x = 2; foo ()} sub foo {print $x}' 222222222 $ perl -e 'for $x (1 .. 9) {my $x = 2; foo ()} sub foo {print $x}' 123456789
        Or is it the fact that Perl just got a little bit more regular that creeps you out?

      ...ah, you're right, I had tried with 5.8.8.

      (/me wonders what that change is supposed to be good for... :)

Re^2: my $1
by ikegami (Patriarch) on Apr 23, 2009 at 20:45 UTC

    Actually, my $_; works in 5.10. It is the only non-alpha variable that can be a lexical, and only a scalar.

    (Oops! got sidetracked after I started replying)

Re^2: my $1
by mltucker (Initiate) on Apr 23, 2009 at 20:49 UTC

    Hi almut,

    Thanks for the reply. Interestingly,

    perl -e 'my $_=1'

    does not complain for me. I'm running v5.10.0.

    local isn't what I'm looking for in this case, but using my $capt1 = $1; worked fine. I guess I'm still perplexed about the $_ vs $1, $2, though. Any ideas?

    -Mark