Friday, January 11, 2013

Perl 에서 Hash table sort 하기기

key 로 sort 하기
 sub sortByKeySample  
 {  
         # define a hash  
         my %v = (20 => "Bee", 30 => "Aeron", 10 => "Dog", 40 => "Cat");  
   
         # sort by value and put the keys in an array   
         my @keys = sort {$a <=> $b} keys %v;  
           
         # loop through array to print the hash pairs ordered  
         foreach my $key (@keys)  
         {  
          print "$key: $v{$key}\n";  
         }  
 }  
value 로 sort 하기 (ascending order)
 sub sortByValueSample  
 {  
         # define a hash  
         my %v = (v1 => 75, v2 => 251, v3 => 3, v4 => 12);  
   
         # sort by value and put the keys in an array   
         my @keys = sort {$v{$a} <=> $v{$b}} keys %v;  
           
         # loop through array to print the hash pairs ordered  
         foreach my $key (@keys)  
         {  
          print "$key: $v{$key}\n";  
         }  
 }  
value 로 sort 하기 (descending order)
 sub sortByValueDescendingSample  
 {  
         # define a hash  
         my %v = (v1 => 75, v2 => 251, v3 => 3, v4 => 12);  
   
         # sort by value and put the keys in an array   
         my @keys = sort {$v{$b} <=> $v{$a}} keys %v;  
           
         # loop through array to print the hash pairs ordered  
         foreach my $key (@keys)  
         {  
          print "$key: $v{$key}\n";  
         }  
 }  
레퍼런스 : Perl sort Function
키워드 : 해쉬, dictionary, 사전, 정렬

No comments:

Post a Comment