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

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

Thread Previous | Thread Next
From:
Ed Avis
Date:
January 27, 2011 03:17
Subject:
Re: Changing variable to numeric without assignment (was: Using smart matching)
Message ID:
loom.20110127T121035-115@post.gmane.org
Abigail <abigail <at> abigail.be> writes:

>>>>>   $ perl -E '$a = $b = "abc100"; 0 + $b; say $a; say $b;
>>>>>              $a ++; $b ++; say $a; say $b'

>>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.

>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.

I see.  Personally, I'd take 'correct, but slightly slower' over 'a bit faster
in some cases, with surprising edge cases' any day.  But isn't it possible to
have it both ways?  The numeric value could be cached in the scalar and used
next time, but without flipping the switch to mark the scalar as numeric.  Then
later numeric context uses would be fast, but the value would not mysteriously
change.

I have only a loose idea of Perl internals so please forgive my ignorance here;
from a user's point of view not changing a variable just because it was *read*
in an arithmetic expression is definitely the right thing to do, but I am
uncertain of the practicalities of doing so in the perl interpreter.

-- 
Ed Avis <eda@waniasset.com>


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