Sunday, May 19, 2013

Perl 에서 hash 를 print 하는 법

 sub printHash_stringKey  
 {  
      my $v = shift;  
      my @keys = sort {$a cmp $b} keys %$v;  
      foreach my $key (@keys)  
      {  
           print "$key: $v->{$key}\n";  
      }  
 }  
 sub printHash_intKey  
 {  
      my $v = shift;  
      my @keys = sort {$a <=> $b} keys %$v;  
      foreach my $key (@keys)  
      {  
           print "$key: $v->{$key}\n";  
      }  
 }  
호출은 printHash(\%hash); 와 같이 하면 됨


Value 로 sort 하는 방법
 sub sortHashByValue  
 {  
      my $hash = shift;  
      my @keys = sort {$hash->{$b} <=> $hash->{$a}} keys %$hash;  
      foreach my $key (@keys)   
      {   
           print "$key: $hash->{$key}\n";  
      }  
 }  

No comments:

Post a Comment