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

Well, the title pretty much asks the question.
Let's say I have a hash like this:

<code>

open FILE, "dir/filename.ext";
while (!eof(FILE)) {
$file = <FILE>;
@pairs = split(/&/, $file);
foreach $pair (@pairs) {
($user, $pass, $bgcolor, $fgcolor) = split(/:/, $pair);
$passwords{$fuser} = $fpass;
$bgcolors{$fuser} = $fbgcolor;
$fgcolors{$fuser} = $ffgcolor;
$usernames{$fuser} = $fuser;
}
}
<code>

Now how can I sort through these alphabetically and print them to the screen?
Thanks ahead of time. :-)

Replies are listed 'Best First'.
Re: Alphabetically sorting hashes
by lhoward (Vicar) on Jun 02, 2000 at 23:37 UTC
    to sort out and print a hash alphabetically based on key:
    foreach(sort keys %hash){ print "$_ -> $hash{$_}\n"; }
    to sort out and print a hash alphabetically based on value:
    foreach(sort {$hash{$a} cmp $hash{$b}} keys %hash){ print "$_ -> $hash{$_}\n"; }
    Now specifically to fit your question:
    foreach(sort keys %usernames){ print "$_ $passwords{$_} $bgcolors{$_} $fgcolors{$_}\n"; }
Re: Alphabetically sorting hashes
by KM (Priest) on Jun 02, 2000 at 23:37 UTC
    What do you want that this doesn't do?

    print qq($_ => $hash{$_}) for sort keys %hash;

    Cheers,
    KM

Re: Alphabetically sorting hashes
by cwest (Friar) on Jun 02, 2000 at 23:36 UTC
    my %hash = ( one =&gt; 1, two =&gt; 2, three =&gt; 3 ); print foreach sort keys %hash;
    Enjoy
    --
    Casey