in reply to Re: Printing hash
in thread Printing hash

Actually, ( sort keys %hash ) creates a list, not an anonymous array (see sort and keys). Anonymous arrays are created using square brackets (see perlref). Please see (tye)Re: What is the difference between a list and an array? for a nice explanation of the difference between lists and arrays (thanks, tye).

Secondly, $key is an alias to each value in the list, which means modifying $key will modify the original value (see perlsyn), as the following example shows:

use strict; use warnings; my @array = ( 1 .. 5 ); foreach my $value ( @array ) { $value--; } print join( ', ', @array ), "\n"; # 0, 1, 2, 3, 4

HTH

Update: added links for sort, keys, and (tye)Re: What is the difference between a list and an array?.

Replies are listed 'Best First'.
Re^3: Printing hash
by CountOrlok (Friar) on Feb 13, 2006 at 05:37 UTC
    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