The example I gave could also be expanded to include a subroutine to
simplify getting a hash value...

%hash = ( one => 1, two => 2 );
$hash{oneagain} = \$hash{one};

foreach my $key ( keys %hash ) {
        # Either will work, but I prefer the second
        print "$key => ".getVal(\%hash, $key)."\n";
        print "$key => @{[getVal(\%hash, $key)]}\n";
}

sub getVal {
        my $hash = shift;
        my $key = shift;

        if (ref $hash->{$key}) {
                return ${$hash->{$key}};
        }
        else {
                return $hash->{$key};
        }
}

Rob

-----Original Message-----
From: Hanson, Robert 
Sent: Friday, February 01, 2002 1:04 PM
To: 'Balint, Jess'; '[EMAIL PROTECTED]'
Subject: RE: Hash Question


Just one unless you use references.  

Here is an example with references...

%hash = ( one => 1, two => 2 );
$hash{oneagain} = \$hash{one};

foreach my $key ( keys %hash ) {
        my $value = (ref $hash{$key}) ? ${$hash{$key}} : $hash{$key};
        print "$key => $value\n";
}

.....And when you change the value of either key (directly or by reference)
both values will be changed because they point to the same piece of data.
And if you delete one of the keys the other will still remain.

You can change it by setting up a sub like this (or directly but that would
be messy)...

setVal(\%hash, 'one', 'ONE');
setVal(\%hash, 'oneagain', 'ONE');

sub setVal {
        my $hash = shift;
        my $key = shift;
        my $value = shift;
        
        if (ref $hash->{$key}) {
                ${$hash->{$key}} = $value;
        }
        else {
                $hash->{$key} = $value;
        }
}

Rob


-----Original Message-----
From: Balint, Jess [mailto:[EMAIL PROTECTED]]
Sent: Friday, February 01, 2002 12:43 PM
To: '[EMAIL PROTECTED]'
Subject: Hash Question


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

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to