Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I'm having a problem with the assignment of multidimensional hashes:
$i=0; $j=0; while (<FIRE>) { chomp $_; ($fgid[$i], $fvalue, $flat[$i], $flong[$i]) = split /,/, $_; $fval{$flat[$i]}{$flong[$i]}=$fvalue; $i++; }
The input data looks like this
virsfire_199801,-1,39.750000,-179.500000 virsfire_199801,-1,39.750000,-179.000000 virsfire_199801,-1,39.750000,-178.500000 virsfire_199801,-1,39.750000,-178.000000
I'm trying to index fvalue with its latitude and longitude values. Something goes wrong though. For example, when I insert
print "testing: $flat[1], $flong[1]\n"; print "testing: $fval{39.750000}{-179.000000}\n"; print "testing: $fval{$flat[1]}{$flong[1]}\n";
I get the following output:
# ./join.pl testing: 39.750000, -179.000000 testing: testing: -1 [root@localhost newstore]#
It seems as if I'm not indexing on the numerical values, but rather on the variable names. Why is this? Thank you, oh monks.

Replies are listed 'Best First'.
Re: multidimenional hashes
by fglock (Vicar) on Oct 11, 2002 at 12:46 UTC

    This is a case when you have to use "", because you are using formatted numbers, that must be kept as strings.

    $fval{"$flat[$i]"}{"$flong[$i]"}
      fglock, and the others, are correct. Here is my version of your last 3 print statements:
      print qq|testing: $flat[1], $flong[1]\n|; print qq|testing: $fval{"39.750000"}{"-179.000000"}\n|; print qq|testing: $fval{"$flat[1]"}{"$flong[1]"}\n|;
      The "qq" operator lets you use whatever you want to use as the delimiter of the string - I chose to use the pipe(|) since the string itself contains double quotes, *and* my other favoite choice for qq operator, {}. HTH.
      Thanks. But does that mean that I have no way of referencing a hash value by giving an "index + offset"? For example, I want to be able to say things like
      $fval{$flat[$i]+0.25}{$flong[$i]}
        You can, you just have to format the value:
        $fval{sprintf('%3.6f', $flat[$i]+0.25)}{$flong[$i]}

        Maybe you'd better be sure that your keys are are not formatted numbers:

        $fval{$flat[$i]+0}{$flong[$i]+0}