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

I have a hash..

%hash=('A'=>1, 'B'=>2, 'C'=>3, 'D'=>4);

..if I want to print this hash I have previously done:

@keyarr=(keys (%hash)); foreach (@keyarr) {print hash{$_}=>$_;

Now I have discovered that the following is possible:

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

Could someone of you please explain what is happening here?
Is an array without name created that holds all the key values and each of the elements is called '$key'? It looks from the code like the $key variable is assigned all keyvalues at one time, this clearly can not be the case so what is going on?

Edited by planetscape - added code tags

Replies are listed 'Best First'.
Re: Printing hash
by mbeast (Beadle) on Feb 13, 2006 at 02:42 UTC
    keys %hash returns an array of keys.

    sort returns an array sorted in ascii table order.

    So you are getting a list (array) of keys, then sorting that list.

    Then the foreach iterates over each element in our new list with each element assigned to '$key' until we run out of elements

    $key will contain 'A', 'B', etc. so we can access our array values with $hash{$key}
Re: Printing hash
by helphand (Pilgrim) on Feb 13, 2006 at 02:29 UTC

    The code:

    foreach my $key (sort keys %hash)

    creates an anonymous array of the sorted keys in the hash %hash. The foreach is a loop construct, each iteration thru the loop sets $key to the next item in the anonymous array until the end of the array, when the loop ends.

    Scott

        Quote:Secondly, $key is an alias to each value in the list, which means modifying $key will modify the original value :EndQuote

        It will change the value in the list returned by keys and sort, but not in the original hash, e.g.

        my %hash = (1 => 'a', 2 => 'b', 3 => 'c'); foreach my $value (sort keys %hash ) { $value--; } print join( ', ', sort keys %hash ), "\n"; # 1, 2, 3
        -imran