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

Hi, I am a Perl newbie so please bear with me.
I was trying to get the keys of an hash element but stumbled across the fact that the interpreter
doesn't seem to like this and thus produces an error. So what I basically want to do is something like the following :
foreach $value ( sort ( keys ( $tophash { $subhash } ) ) ); { print "$value"; }
What is the right way to accomplish this? Any help is appreciated. Thanks

Mandor

Replies are listed 'Best First'.
(Guildenstern) Re: Getting keys of a hash element
by Guildenstern (Deacon) on Jan 25, 2001 at 00:22 UTC
    I'm unsure what kind of hash you have here. If you're wanting to get the keys of %tophash in sorted order, try this:
    foreach my $value (sort keys %tophash) { print $value; }


    If, on the other hand $tophash{$subhash} is a reference to a hash, you'll need to do something like this:
    foreach my $value (sort keys %{$tophash{$subhash}}) { print $value; }


    Guildenstern
    Negaterd character class uber alles!
      It was the 2nd one and it worked perfectly. Thanks!
Re: Getting keys of a hash element
by Gloom (Monk) on Jan 25, 2001 at 02:50 UTC
    you can also use smarts shortcuts
    print sort keys %hash;
    or
    print join "\n" , sort keys %hash;
    if you need some separators.
Re: Getting keys of a hash element
by mr.nick (Chaplain) on Jan 25, 2001 at 00:34 UTC
    Perhaps this example will help
    foreach $key (sort keys %tophash) { foreach $subkey (sort keys %{$tophash{$key}}) { print "$key/$subkey = $tophash{$key}{$subkey}\n"; } }
Re: Getting keys of a hash element
by Trinary (Pilgrim) on Jan 25, 2001 at 00:28 UTC
    Getting keys of a hash _element_ or getting keys of a hash? The latter would imply that the hash values are references to more hashes, which is very different. Example of the simple case:

    foreach $key (sort(keys(%hash))) { print "Key = $key, value= $hash{$key}\n"; }

    The whole reference can o' worms looks somethin like this:

    foreach $key (sort(keys(%hash))) { print join(/ /,keys(%{$hash{$key}}),"\n"; }
    There's probably about a million typos in there, but someone will correct me. =) That'll print out a line with the keys contained in the hash referred to by the values of %hash. Not sure if this is what you want, I'm guessing the first solution is closer to what you mean...

    enjoy

    Trinary