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

in a foreach (keys %hash) how do you save the key inside a variable?  foreach my $key (keys %hash) seems to mess things up. I also tried  my $value = $hash{$_}.

Replies are listed 'Best First'.
Re: saving the key of a hash
by NetWallah (Canon) on May 13, 2004 at 04:41 UTC
    One interpretation of the question is that you are looking for a way to save A particular key. Assuming this is what you want to do, here is some pseudo-code (untested).
    my $SaveKey; while (my ($key, $val) = each %hash){ if (WHatever condition){ $SaveKey = $key; # Save this one } } my $SavedValue = $hash{$SaveKey}; # Use the saved key, if any

    Offense, like beauty, is in the eye of the beholder, and a fantasy.
    By guaranteeing freedom of expression, the First Amendment also guarntees offense.
Re: saving the key of a hash
by coec (Chaplain) on May 13, 2004 at 00:37 UTC
    save the key inside a variable?
    What do you mean? What are you actually trying to achieve?
Re: saving the key of a hash
by Anonymous Monk on May 13, 2004 at 00:43 UTC
    Is this what you want?
    foreach my $variable (keys %hash){ my $value = $hash{$variable}; print "$variable\t$value\n"; }
Re: saving the key of a hash
by dave_the_m (Monsignor) on May 13, 2004 at 12:00 UTC
    "seems to mess things up". Perhaps you could give an example?
Re: saving the key of a hash
by tbone1 (Monsignor) on May 13, 2004 at 12:31 UTC
    To save the key, try:

    my $value = $_;
    because $hash{$_} is the value of the array element, not the key.

    --
    tbone1, YAPS (Yet Another Perl Schlub)
    And remember, if he succeeds, so what.
    - Chick McGee