On Wed, Nov 21, 2012 at 01:20:19AM +0100, Dr.Ruud wrote: > On 2012-11-20 22:57, Lukas Mai wrote: > >On 19.11.2012 18:17, sp@smartspb.net (via RT) wrote: > > >>Successfull match $_[0] =~ /foo(.+)/ inside subroutine > >>overrides $_[0] if subroutine called as foo($1). > >> > >>###### script ###### sp@uskr:~/3 (1570) cat u.pl > >>use strict; use warnings; use feature qw(:all); > >> > >>sub foo { > >> say ' before =~ $_[0] is ', "'$_[0]'"; > >> $_[0] =~ /foo(.+)/; > >> say ' after =~ $_[0] is ', "'$_[0]'", ' and $1 is ', "'$1'"; > >>} > >> > >># ok > >> > >>say 'call foo("foo123");'; > >>foo('foo123'); > >> > >># at least strange > >> > >>say 'call foo($1);'; > >>'barfoo123' =~ /(foo.+)/ && foo($1); > >> > >>###### output ###### sp@uskr:~/3 (1571) perl u.pl > >> > >>call foo("foo123"); > >> before =~ $_[0] is 'foo123' > >> after =~ $_[0] is 'foo123' and $1 is '123' > >>call foo($1); > >> before =~ $_[0] is 'foo123' > >> after =~ $_[0] is '123' and $1 is '123' > >> > >>sp@uskr:~/3 (1572) > >> > >>###### summary ###### > >> > >>I'm not sure is that bug or feature. > >>I could not find something describing such things in docs. > > > >This is not a bug. Quoting perldoc perlsub: > > > >Any arguments passed in show up in the array @_ . Therefore, if you > >called a function with two arguments, those would be stored in $_[0] and > >$_[1] . The array @_ is a local array, but its elements are aliases for > >the actual scalar parameters. In particular, if an element $_[0] is > >updated, the corresponding argument is updated (or an error occurs if it > >is not updatable). If an argument is an array or hash element which did > >not exist when the function was called, that element is created only > >when (and if) it is modified or a reference to it is taken. (Some > >earlier versions of Perl created the element whether or not the element > >was assigned to.) Assigning to the whole array @_ removes that aliasing, > >and does not update any arguments. > > Workaround: local $1. (at the start of the sub) > > Do we need a feature that auto-localizes the numbered capture > variables for subs? No. The behavior here is the same behavior as my $a; sub foo { say $_[0]; $a = "bar"; say $_[0]; } $a = "foo"; foo($a); which prints foo bar It has nothing to do with capture variables, it happens for any variable at all, because it is caused by the aliasing, not anything about the variable itself. -doyThread Previous | Thread Next