Saturday, January 12, 2013

Perl 에서 array of arrays 를 특정 field 로 sort 하는 법

다음 참조하기: Perl 에서 sort 하기 / sort 된 array 에 새 item 삽입하기
-------------
예를 들어 12번째 field 로 sort 한다면
@AoA = sort { $a->[12] <=> $b->[12] } @AoA
예 1:
 my @aofa = ();  
 my @a = ("Glen Benton", 92);  
 my @b = ("Jimi Hendrix", 27);  
 my @c = ("Oda Nobunaga", 47);  
 my @d = ("Christ", 33);  
 push(@aofa, \@a);  
 push(@aofa, \@b);  
 push(@aofa, \@c);  
 push(@aofa, \@d);  
   
 for (@aofa) {  
   print "@$_"; print "\n";  
 }  
 print "\n";  
   
 my @sorted = sort {$a->[1] cmp $b->[1]} @aofa;  
   
 for (@sorted) {  
   print "@$_"; print "\n";  
 }  
 print "\n";  
예 2:
 my @AoA = (  
   ['a', '2003-11-09', 'b'],  
   ['c', '2003-11-01', 'd'],  
   ['e', '2002-11-01', 'f'],  
   ['g', '2003-10-01', 'h'],  
   ['g', '2002-10-01', 'h'],  
 );  
   
 #my @new_arr = sort {$a->[0] cmp $b->[0]} @AoA;  
 my @new_arr = sort {$a->[1] cmp $b->[1]} @AoA;  
 #my @new_arr = sort {$a->[2] cmp $b->[2]} @AoA;  
   
 for (@new_arr) {  
   print "@$_"; print "\n";  
 }  
출처 : http://www.sitepoint.com/forums/showthread.php?659680-Perl-Sort-Array-of-Arrays
키워드 : 정렬

No comments:

Post a Comment