Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does the difference between a string and a number matter in Perl 5?

If a string in Perl 5 passes looks_like_number, it might as well be a number. For instance,

my $s = "10" + 5;

results in $s being assigned 15.

Are there any cases where a string does not behave like its numeric equivalent would?

like image 486
Chas. Owens Avatar asked Jun 05 '10 13:06

Chas. Owens


4 Answers

When dealing with bitwise operators. 123 ^ 456 is 435, but "123" ^ "456" is "\x05\x07\x05". The bitwise operators work numerically if either operand is a number.

like image 185
hobbs Avatar answered Oct 17 '22 21:10

hobbs


I can only think of one: when checking for truth. Strings that are equivalent to 0, but that are not "0", such as "0.0", "0 but true", "0e0", etc. all pass looks_like_number and evaluate to 0 in numeric context, but are still considered true values.

like image 29
Chas. Owens Avatar answered Oct 17 '22 21:10

Chas. Owens


An equivalent number and string behave differently in hash keys -- or, more generally, any time we stringify a largish number:

my (%g, %h);
$g{ 1234000000000000 } = undef;  # '1.234e+015'       => undef
$h{'1234000000000000'} = undef;  # '1234000000000000' => undef

Note that we are still within the range where Perl can store the number precisely:

> perl -e 'printf qq{%.f\n}, 1234000000000000 + $_ for +1, 0, -1'
1234000000000001
1234000000000000
1233999999999999
like image 22
FMc Avatar answered Oct 17 '22 23:10

FMc


  DB<1> sub is_num { my $x = shift; "$x " ~~ $x }

  DB<2> print is_num(123)
1
  DB<3> print is_num('123')

  DB<4> 
like image 2
abufct Avatar answered Oct 17 '22 22:10

abufct