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 28, 2011 03:37
Subject:
Re: Changing variable to numeric without assignment (was: Using smart matching)
Message ID:
loom.20110128T123137-351@post.gmane.org
Abigail <abigail <at> abigail.be> writes:

>>|       The auto-increment operator has a little extra builtin magic to
>>|       it. If you increment a variable that is numeric, or that has
>>|       ever been used in a numeric context, you get a normal increment.
>>|       If, however, the variable has been used in only string contexts
>>|       since it was set, and has a value that is not the empty string
>>|       and matches the pattern "/^[a-zA-Z]*[0-9]*\z/", the increment is
>>|       done as a string, preserving each character within its range,
>>|       with carry:

> Note that the documentation the quote contains a couple of white lies.
>
>    $a = "foo123";
>    0 + $a;    # Use the variable $a in numeric context
>    $b = $a;
>    $a = "bar456";
>    $a ++;
>    $b ++;
>    say $a;    # Prints 'bar457';
>    say $b;    # Prints '1';

The documentation is a little inconsistent; $a 'has ever been used in
a numeric context', but also 'has been used only in string contexts since it
was set'.  So either case could apply.

Rather than these mealy-mouthed ways of hinting at the internal state of a
scalar, it might be better to come out and expose the dual-valued nature of
scalars to the programmer, so you can say 'when done on strings, ++ has some
magic, and when done on numbers, it adds one'.  But that would require quite
a change to the way we think about Perl programming.  The casual Perl coder is
not really aware of when a scalar is represented as a string or number, and
usual tutorial material does not encourage thinking about it.

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