in reply to Numeric as hash key returns undef...

Are you certain that your hash keys are what you think they are? If you're doing floating-point math, you may end up with keys that have more decimal places. Even an integer like 5.00 might be stringifying as 5.00000001 if there's FP math involved.

Try using Data::Dumper on your hash to see if that's the case.

  • Comment on Re: Numeric as hash key returns undef...

Replies are listed 'Best First'.
Re^2: Numeric as hash key returns undef...
by Joost (Canon) on Oct 24, 2006 at 21:22 UTC
    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. :-)

      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.

        ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

      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.