in reply to Re: Numeric as hash key returns undef...
in thread Numeric as hash key returns undef...

Oh yes, good catch :-)

(to the OP) - hash keys are always regarded as strings - that means you should make sure your numeric keys are represented as exactly the right string. I.e. $hash{1.0} is not the same as $hash{1}*. One way of doing that is to use sprintf. For example, if all your keys have 2 places behind the comma, you can use something like this:

my $key = sprintf("%0.2f",$number); my $value = $hash{$key}
Actually, it is. But $hash{"1.0"} is not the same as $hash{1.0} go figure. :-)

Replies are listed 'Best First'.
Re^3: Numeric as hash key returns undef...
by Anonymous Monk on Oct 24, 2006 at 21:40 UTC
    It actually gets weirder than that -- the . (concatenation) operator has higher precedence than a hash's auto-stringification. This confused a somewhat baffling bug for a few hours recently...
    use Data::Dumper; $x{a} = "bare a"; $x{"a.b"} = "quoted a.b"; $x{a.b} = "unquoted a.b"; print Dumper(\%x);' __DATA__ $VAR1 = { 'ab' => 'unquoted a.b', 'a.b' => 'quoted a.b', 'a' => 'bare a' };

      a.b cannot be auto-stringified because it does not match the pattern ^\w+$. What you're observing is the valid perl a.b becomng 'a'.'b' because strict allowed your bareword strings to be unquoted. At this point this has nothing to do with being a hash key. It's just that they're an expression. Enable strict to see what you were missing.

      ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

Re^3: Numeric as hash key returns undef...
by journey (Monk) on Oct 25, 2006 at 13:36 UTC
    Thanks to all for your help.
    My mistake was effectively to have another hash where the keys were not quoted hence the "undef" for key 5.00 when multiplying. I hope I did not abuse of your time. Many thanks again.