Front page | perl.beginners |
Postings from February 2002
RE: Hash Question
Thread Previous
|
Thread Next
From:
Balint, Jess
Date:
February 1, 2002 11:50
Subject:
RE: Hash Question
Message ID:
CA8ED43817EFD211855E00805FE6FD7403AA1943@scadmail2.alldata.net
I think I will go ahead and use something like the multi-dimensional hash
example below. What I need to do is create hashes dynamically based on how
many are needed for this particular instance of the program. Any ideas on
dynamic hash creation multi-dimensionally? Thanks -jess
-----Original Message-----
On Fri, 2002-02-01 at 12:42, Balint, Jess wrote:
> Since this is a beginners list, I thought I would be allowed to ask this
> question. Can there be multiple values for hash keys, or just one? The
> reason I am asking is that I am working on a statistical program and would
> need to use multiple hashes as values of another hash. If this is
possible,
> please let me know. Thank you.
>
> -Jess
>
I assume you mean a multi-dimensional hash. Perl allows infinite
(assuming you have the resources) nesting of data structures. This is
accomplished by using a reference to the structure to be nested. So for
a three dimension hash you would first have a hash whose values were
hash references. Then those hashes would have values that were also
references to hashes. You could then access the data like this:
print $hash{'key1'}->{'key2'}->{'key3'}, "\n";
but Perl being what it is provides a little syntatic suger and lets you
just write this:
print $hash{'key1'}{'key2'}{'key3'}, "\n";
<example>
#!/usr/bin/perl -w
use strict;
my %hash;
while (<>) {
my ($key1, $key2, $key3, $data) = split;
$hash{$key1}{$key2}{$key3} = $data if $key1 and $key2 and $key3;
}
foreach my $key1 (sort keys %hash) {
foreach my $key2 (sort keys %{$hash{$key1}}) {
foreach my $key3 (sort keys %{$hash{$key1}{$key2}}) {
print "($key1)+($key2)+($key3) returns ",
$hash{$key1}{$key2}{$key3}, "\n";
}
}
}
</example>
--
Today is Boomtime the 32nd day of Chaos in the YOLD 3168
Or is it?
Missle Address: 33:48:3.521N 84:23:34.786W
Thread Previous
|
Thread Next