develooper Front page | perl.perl5.porters | Postings from November 2012

Re: [perl #115834] Successfull match $_[0] =~ /foo(.+)/ overrides$_[0] if function called as foo($1)

From:
Jesse Luehrs
Date:
November 25, 2012 11:01
Subject:
Re: [perl #115834] Successfull match $_[0] =~ /foo(.+)/ overrides$_[0] if function called as foo($1)
Message ID:
20121125190134.GS13346@tozt.net
On Wed, Nov 21, 2012 at 03:55:43AM -0800, Ed Avis via RT wrote:
> On Tue Nov 20 16:26:18 2012, doy@tozt.net wrote:
> 
> >The behavior here is the same behavior as
> 
> I believe it's not the same behaviour as the example you gave.
> Expanding the code with one more final 'say':
> 
>     my $a;
>     sub foo {
>         say $_[0];
>         $a = "bar";
>         say $_[0];
>     }
>     $a = "foo";
>     foo($a);
>     say $a;
> 
> This prints foo bar bar.  But the analogous code using $1
> 
>     sub foo {
>         say $_[0];
>         'bar' =~ /(bar)/;
>         say $_[0];
>     }
>     'foo' =~ /(foo)/;
>     foo($1);
>     say $1;
> 
> prints foo bar foo.  So while in the case of a global variable you set
> the value seen by the caller - which makes sense - here $1 is aliased
> enough to cause weird effects inside the subroutine, yet somehow local
> enough for these effects to disappear when the subroutine exits.  This
> halfway house is what causes the confusion IMHO.

This is just a side effect of how $1 works in general - any assignments
to capture variables (via a successful match) are implicitly localized:

  "foo" =~ /(.*)/;
  warn $1;
  {
      "bar" =~ /(.*)/;
      warn $1;
  }
  warn $1;

also outputs

  foo
  bar
  foo

The current behavior is the only thing that actually makes sense, given
the combination of behaviors in this example and the previous one I
gave. I do agree that it's fairly confusing, but I really don't know
what a better solution to this could possibly be.

-doy



nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About