Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Squeezing $a+1 to be magical like $a++

by jeroenes (Priest)
on Oct 10, 2001 at 14:16 UTC ( #117964=note: print w/ replies, xml ) Need Help??


in reply to Squeezing $a+1 to be magical like $a++

There is Yet Another Reason why you really don't want to magicalize the adding operator, and that is the way it handles alphanumeric characters. E.g., 'z9' with ++ becomes 'aa0'. What would you want to do with 'z9' + 'a04'? That promises to get unbelievable messy. And we even haven't touched the subject of fractions... I suggest you leave the magic alone and use sprintf instead.

sub format_add{ my ($x, $y) = @_; my $ret = $x + $y; my $digs = length $x; sprintf("%0${digs}d", $ret ); }
Of course you can overload the '+' with this sub.


The ++ can do some strange things, by the way:
$a=0.5; print ++$a; #prints 1.5 $a='a0.5'; print ++$a; #prints a6 #(so ++ ignores the dot and squashes the 0) $a='2a'; print ++$a; #prints 3 #(because 2a in numeric context returns 2)

Apparently it is a beast to handle with care.

Jeroen
"We are not alone"(FZ)


Comment on Re: Squeezing $a+1 to be magical like $a++
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://117964]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (10)
As of 2014-07-30 03:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (229 votes), past polls