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)

Thread Previous | Thread Next
From:
Lukas Mai
Date:
November 20, 2012 13:58
Subject:
Re: [perl #115834] Successfull match $_[0] =~ /foo(.+)/ overrides$_[0] if function called as foo($1)
Message ID:
50ABFCC4.5010903@web.de
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.



-- 
Lukas Mai <l.mai@web.de>

Thread Previous | Thread Next


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