Although a documented one... basically I just want to report an interesting entry in the Journal of DAxelrod (who is also a fellow monk here), at use Perl.
To cut it short, the following:
#!/usr/bin/perl use strict; use warnings; my ($num, $let, $foo); $num = "z"; $let = $num; # $foo = 1 + $num; # this does not modify $num $num++; $let++; print "num:$num let:$let\n"; __END__
outputs
num:aa let:aa
whereas if you uncomment line 9, it will issue a
Argument "z" isn't numeric in addition (+) at C:\temp\foo.pl line 9.
warning, and output
num:1 let:aawhich is as of the subject, surprising and unexpected due to the fact that $num is just used, but appearently not modified in any way whatsoever. However, as the original article itself says this is both documented and useful for obfu. In this respect I was thinking that a particularly confusing effect could be achieved if one used e.g. "9" instead of "z", but that doesn't seem to be the case:
C:\temp>perl -le "$a='z';print++$a" aa C:\temp>perl -le "$a='9';print++$a" 10
B::Concise seems to say the same for both:
C:\temp>perl -MO=Concise -e "$a='z'" >z -e syntax OK C:\temp>cat z 6 <@> leave[1 ref] vKP/REFC ->(end) 1 <0> enter ->2 2 <;> nextstate(main 1 -e:1) v ->3 5 <2> sassign vKS/2 ->6 3 <$> const[PV "z"] s ->4 - <1> ex-rv2sv sKRM*/1 ->5 4 <#> gvsv[*a] s ->5 C:\temp>perl -MO=Concise -e "$a='9'" >9 -e syntax OK C:\temp>diff z 9 5c5 < 3 <$> const[PV "z"] s ->4 --- > 3 <$> const[PV "9"] s ->4
(Note: damn! I couldn't use | diff z - under Windows.)
Fortunately, this is perfectly well documented as well:
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.
This obviously mean that "that is numeric" comprises "that looks like a number". How much it may resemble one, though, is not very intuitive. I do know it's more or less Perl's standard behaviour, but I for one would expect the string to be treated as a string in both of the following:
C:\temp>perl -le "$a='foo9';print++$a" fop0 C:\temp>perl -le "$a='9bar';print++$a" 10
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: A somewhat unexpected side effect...
by Anonymous Monk on Nov 21, 2006 at 12:14 UTC | |
by blazar (Canon) on Nov 22, 2006 at 16:14 UTC | |
Re: A somewhat unexpected side effect... (stringy)
by tye (Sage) on Nov 21, 2006 at 16:06 UTC |