John W. Krahn wrote:

>Shiping Wang wrote:
>> 
>> Hi,
>
>Hello,
>
>> How can I rearrange an array in a specific order based on the order of a
>> hash? Something like this:
>> 
>> my @a = qw(Mary John Dan);
>> print join "\t", @a, "\n";
>> 
>> my %b = ( John => 0,
>> Dan => 1,
>> Mary => 2);
>> 
>> print "$_ => $b{$_}\n" for (keys %b);
>> print "$_-$b{$_}\t" foreach sort {$b{$a} <=> $b{$b}} keys %b;
>> 
>> The final order for @a expect:  John Dan Mary
>
>
>$ perl -le'
>my @a = qw( Mary John Dan );
>my %b = qw( John 0 Dan 1 Mary 2 );
>print "@a";
>@a = sort { $b{ $a } <=> $b{ $b } } @a;
>print "@a";
>'
>Mary John Dan
>John Dan Mary
>
Smart. But the sort pattern might be easier on the eye the array and hash are not 
named @a and %b.

$ perl -le'
my @array = qw( Mary John Dan );
my %hash = qw( John 0 Dan 1 Mary 2 );
print "@array";
@array = sort { $hash{ $a } <=> $hash{ $b } } @array;
print "@array";
'
Mary John Dan
John Dan Mary

This is mainly for my own better understanding.

- Jan
-- 
These are my principles and if you don't like them... well, I have others. - Groucho 
Marx

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to