Re: Assigning a variable to hash keys and values

From: Philipp Traeder (traeder_at_is24.de)
Date: 06/29/04


To: beginners@perl.org
Date: Tue, 29 Jun 2004 10:37:04 +0200

On Tuesday 29 June 2004 08:49, Daniel Falkenberg wrote:
> Hello All,

Hi Dan,

> I currently have a hash of a hash...
>
> > %HoH = (
> > Key1 => {
> > Apple => "Green",
> > Banna => "Yellow",
> > },
> > Key2 => {
> > Carrot => "Orange",
> > Tomoatoe => "Red",
> > },
> > );
>
> How can I assign Key2 to a variable?

# If you want to assign Key2's value, you could so something like:
my $key2_ref = $HoH{Key2};
print "key2_ref : $key2_ref\n";

# Note that $key2_ref contains a hash-ref now, so if you want to use it as a
# hash, you should tell perl that you want to use it as an hash:
my %key2_hash = %{$key2_ref};
print "key2->carrot : " . $key2_hash{Carrot} . "\n";

# You can use the same technique to access the inner hashes:
my $carrot_color = ${$HoH{Key2}}{Carrot};
print "carrot color : $carrot_color\n";
  
# Theres another version of accessing a value of a hash ref
# that more pleasant to the eye:
my $carrot_color2 = $HoH{Key2}->{Carrot};
print "carrot color 2 : $carrot_color2\n";

Take a look at
  perldoc perlreftut

It's a very good (and short) tutorial about references that explains all this
much better than I can.

HTH,

Philipp



Relevant Pages

  • Re: Assigning a variable to hash keys and values
    ... On Tue, 2004-06-29 at 12:19, Daniel Falkenberg wrote: ... > I currently have a hash of a hash... ... I think you mean the value of Key2 to a variable right? ... %hash does not affect the %HoH data ...
    (perl.beginners)
  • Assigning a variable to hash keys and values
    ... I currently have a hash of a hash... ... How can I assign Key2 to a variable? ... Regards, ... Dan ...
    (perl.beginners)
  • Re: [Full-disclosure] Microsoft takes 7 years to solve a problem?!
    ... Hash: SHA1 ... Dan has been an exception to just about every rule, ...
    (Full-Disclosure)
  • Re: Java HashSet Problem
    ... equal using the equals method and they do generate the same hash ... contains key2 method) the answer should be yes. ... However, as you can see, the hash set does not realize that it ...
    (comp.lang.java.programmer)
  • Re: Java HashSet Problem
    ... equal using the equals method and they do generate the same hash ... contains key2 method) the answer should be yes. ... However, as you can see, the hash set does not realize that it ...
    (comp.lang.java.programmer)