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

Silent mutation when using in numeric context (was: Using smart matching...)

Thread Previous | Thread Next
From:
Ed Avis
Date:
January 26, 2011 08:46
Subject:
Silent mutation when using in numeric context (was: Using smart matching...)
Message ID:
loom.20110126T173440-632@post.gmane.org
Abigail <abigail <at> abigail.be> writes:

>>Ah - I do not use the | operator in everyday programming (in fact, I don't
>>think I have ever used it)

>    sysopen $fh, "foo", 0666, O_CREAT | O_EXCL;

OK, yes I have done that - but surprisingly, not in my day job for the past
few years.  Maybe because if something requires locking or atomic access I
tend to store it in an RDBMS instead, and rely on File::Temp for tempfiles.

>>Surely the expression 0 + $b should not mutate the value
>>of $b.  I'm surprised this is not considered a bug?
> 
>I'm pretty sure I'd like $b to get a numerical value if I use it in
>numeric context.

I'd surely like to receive a numerical value when using numeric context.
And I'd like $b to be assigned a numerical value if I wrote an assignment.
But for just mentioning the expression ($b + 0) to cause an assignment to $b -
albeit a subtle one that you don't always notice - seems quite wrong.  The
expression should return a numerical value but leave $b untouched, IMHO.

This oddity leads to an example Readonly changing the semantics of a program:

  my $b = "abc100";
  $a = "abc100"; 0 + $b; $c = $b; $a ++; $c++; print $c;

produces '1', whereas

  use Readonly;
  Readonly my $b => "abc100";
  $a = "abc100"; 0 + $b; $c = $b; $a ++; $c++; print $c;

produces 'abc101'.

That must count as a bug either in Readonly or in perl.  Either $b is modified
or it is not.  If it is not modified, then marking it readonly should make no
difference.  If it is modified, then the Readonly version should fail with a
run time or compile time error at the point where modification is attempted.

-- 
Ed Avis <eda@waniasset.com>




perl -MReadonly -E 'Readonly my $b => "abc100"; $a = "abc100"; 0 + $b; say $a;
say $b; $c = $b; $a ++; $c++\
; say $a; say $c'



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