One way is to make a custom sorting function.  You pass it a list of items
and it goes through the list and compares each via the variables $a and $b.
You make the function return -1 if $a is "smaller than" or "before" $b, 1 if
$a is "bigger than" or "after" $b, or 0 if they are tied.  In this case we
can pass to the sorting function the hash keys for %urls, and then let it
sort by comparing $urls{$a} to $urls{$b}.

########### the long way

my %urls;

$urls{uol} = 1;
$urls{aol} = 2;
$urls{txt} = 3;

foreach (sort by_value keys %urls)
{
        print "$urls{$_} $_\n";
}

sub by_value
{       
        return -1 if $urls{$a} < $urls{$b};
        return 1 if $urls{$a} > $urls{$b};
        return 0;
}

BUT, since our sorting function is so simple, we can make the prog shorter
by just putting the sorting rules in-line, like this:

########## the short way

my %urls;

$urls{uol} = 1;
$urls{aol} = 2;
$urls{txt} = 3;

foreach (sort {$urls{$a} <=> $urls{$b}} keys %urls)
{
        print "$urls{$_} $_\n";
}

>-----Original Message-----
>From: [EMAIL PROTECTED]
>[mailto:[EMAIL PROTECTED] Behalf Of
>Márcio Oliveira
>Sent: Thursday, July 29, 2004 9:47 AM
>To: [EMAIL PROTECTED]
>Subject: [Perl-unix-users] sorting hash values
>
>
>hi!
>
>I need to organize a list of values i a hash, but i don't know how.
>
>ex:
>
>my %urls;
>
>$urls{uol} = 1;
>$urls{aol} = 2;
>$urls{txt} = 3;
>
>## if i use this:
>
>@num = sort keys(%url};
>
>foreach $number(@num) {
>   print $number."\n";
>}
>
>## I have this output:
>
>aol
>txt
>uol
>
>## how i can organize the values and print the values hash 
>"key", with this
>output (sorted by hash values):
>
>1 uol
>2 aol
>3 txt
>
>thank's
>
>Atenciosamente,
>
>Márcio Oliveira
>LPIC-1
>
>
>_______________________________________________
>Perl-Unix-Users mailing list
>[EMAIL PROTECTED]
>To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs
>


_______________________________________________
Perl-Unix-Users mailing list
[EMAIL PROTECTED]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to