develooper Front page | perl.perl5.porters | Postings from January 2011

Re: Changing variable to numeric without assignment (was: Usingsmart matching)

Thread Previous | Thread Next
From:
Abigail
Date:
January 27, 2011 03:06
Subject:
Re: Changing variable to numeric without assignment (was: Usingsmart matching)
Message ID:
20110127110554.GU8853@almanda
On Thu, Jan 27, 2011 at 10:39:20AM +0000, Ed Avis wrote:
> Konovalov, Vadim <vadim.konovalov <at> alcatel-lucent.com> writes:
> 
> >>>   $ perl -E '$a = $b = "abc100"; 0 + $b; say $a; say $b;
> >>>              $a ++; $b ++; say $a; say $b'
> >> 
> >>That is a nasty one.  Surely the expression 0 + $b should not 
> >>mutate the value of $b.
> 
> >  perldoc Scalar::Util
> > 
> >dualvar section?
> 
> Thanks for the pointer.  I hadn't read that although I was aware of the common
> 'zero but true' trick.
> 
> However the existence of dual-valued variables isn't the issue here.  The point
> is that just evaluating the expression ($b + 0) in some other code, even if you
> do not assign the result to $b or try to change $b in any way, has the
> unexpected side-effect of changing the value stored in $b.  That can't be right.
> 


Not changing the value stored in $b means that

    my ($a) = /([0-9]+)/;
    @foo = map {$_ + $a} @bar;

becomes more expensive, and $a will need to be converted from string to
integer for each element of @bar, instead of doing it once and caching
the result.



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