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

Re: unexpected result of stringification.

Thread Previous | Thread Next
From:
abigail
Date:
March 18, 2001 07:04
Subject:
Re: unexpected result of stringification.
Message ID:
20010318150738.32598.qmail@foad.org
On Mon, Mar 12, 2001 at 12:30:43PM +0000, David Mitchell wrote:
> 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.

Yes, for calling functions. And that's documented. But perlop says:

    The `||' and `&&' operators differ from C's in that, rather than
    returning 0 or 1, they return the last value evaluated.

It clearly states *value*. Not address. Not alias. Value.

And before you say it's because print is being called and that's a function,
you are wrong. That's irrelevant; it's about what && returns.

    $a = (($foo = 2) && $foo) + (($foo = 3) && $foo);
    print $a;

prints 6, not 5 as you would expect if && returns a value.

Camel III agrees with perlop that && and || return values.


Abigail

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