develooper Front page | perl.perl5.porters | Postings from March 2001

Re: unexpected result of stringification.

Thread Previous | Thread Next
From:
David Mitchell
Date:
March 12, 2001 04:30
Subject:
Re: unexpected result of stringification.
Message ID:
200103121230.MAA19614@tiree.fdgroup.co.uk
Konovalov, Vadim" <vkonovalov@lucent.com> wrote:

> print 'foo'=~/(.*)/ &&  $1,   'bar'=~/(.*)/ && $1,  "\n";
> print 'foo'=~/(.*)/ && "$1", 'bar'=~/(.*)/ && "$1", "\n";
> 
> 
> results in:
> 
> barbar
> foobar
> 
> which was unexpected to me.
> While there may be found a way to explain such behaviour, it may result in
> errors that are quite hard to find.

This is not a bug.

It occurs due to the way parameters to functions are handled.

if you call foo($var), then within foo(), $_[0] does not contain a *copy*
of the current value of $var; instead $_[0] is an *alias* of $var - ie
modifying $_[0] actually modifies $var.

Or to put is another way: behind the scenes, foo($var) causes the address
of $var to be passed to foo, rather than its current value being passed.

On the other hand, foo($var+1) causes the expression $var+1 to be evaluated
before the function is called, and the resulting value passed as a read-only
variable to the function.

print 'foo'=~/(.*)/ &&  $1,   'bar'=~/(.*)/ && $1,  "\n";

does the rough equivalent of:

$1 = 'foo';
addressof($_[0]) = addressof($1);
$2 = 'bar';
addressof($_[1]) = addressof($1);
addressof($_[2]) = addressof(readonly_variable("\n"));
print;
Then within print(), its 1st two arguments are both aliased to $1, which
happens to to have the value 'bar';

On the other hand,

print 'foo'=~/(.*)/ && "$1", 'bar'=~/(.*)/ && "$1", "\n";

does the rough equivalent of:

$1 = 'foo';
addressof($_[0]) = addressof(readonly_variable("foo"));
$2 = 'bar';
addressof($_[1]) = addressof(readonly_variable("bar"));
addressof($_[2]) = addressof(readonly_variable("\n"));
print;


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