sorté¢æ° - é åã®ä¸¦ã¹æ¿ã
ãé åã並ã¹æ¿ããã«ã¯sorté¢æ°ã使ç¨ãã¾ãã第1å¼æ°ã«ã¯æ¯è¼ã®ããã®ã³ã¼ããããã¯ã渡ãã¾ããæé ã§ä¸¦ã¹æ¿ããå ´åã¯$aã$bããå ã«è¨è¿°ããéé ã§ä¸¦ã¹æ¿ããã«ã¯$bã$aããå ã«è¨è¿°ãã¾ããæ¯è¼æ¼ç®åã«ã¯æ°å¤ã¨ãã¦æ¯è¼ãããå ´åã¯<=>ã使ç¨ããè¾æ¸é ã§æ¯è¼ãããå ´åã¯cmpã使ç¨ãã¾ããã³ã¼ããããã¯ã®ç´å¾ã«ã«ã³ãããªããã¨ã«æ³¨æãã¦ãã ããã
# æé ã§ä¸¦ã¹æ¿ã @sorted = sort { $a æ¼ç®å $b } @array; # éé ã§ä¸¦ã¹æ¿ã @sorted = sort { $b æ¼ç®å $a } @array;
並ã³æ¿ãã®ãµã³ãã«
ãæ°å¤ã®æé ã§ä¸¦ã¹æ¿ãããµã³ãã«ã§ãã@numsã¯(2, 3, 5, 11)ã«ãªãã¾ãã
# æ°å¤ã®æé ã§ä¸¦ã³æ¿ã my @nums = (5, 11, 3, 2); @nums = sort {$a <=> $b} @nums;
ãæ°å¤ã®éé ã§ä¸¦ã¹æ¿ãããµã³ãã«ã§ãã@numsã¯(11, 5, 3, 2)ã«ãªãã¾ãã
# æ°å¤ã®éé ã§ä¸¦ã³æ¿ã my @nums = (5, 11, 3, 2); @nums = sort {$b <=> $a} @nums;
ãè¾æ¸é ã®æé ã§ä¸¦ã¹æ¿ãããµã³ãã«ã§ãã@numsã¯(11, 2, 3, 5)ã«ãªãã¾ãã11ã¨3ã¯è¾æ¸é ã§æ¯è¼ããã¨11ã®ã»ããå²ãã«ãã¾ãã
# è¾æ¸é ã®æé ã§ä¸¦ã³æ¿ã my @nums = (5, 11, 3, 2); @nums = sort {$a cmp $b} @nums;
ãè¾æ¸é ã®éé ã§ä¸¦ã¹æ¿ãããµã³ãã«ã§ãã@numsã¯(5, 3, 2, 11)ã«ãªãã¾ãã
# è¾æ¸é ã®éé ã§ä¸¦ã³æ¿ã my @nums = (5, 11, 3, 2); @nums = sort {$b cmp $a} @nums;
ã³ã¼ããããã¯ã®çç¥
ãã³ã¼ããããã¯ãçç¥ããå ´åã¯è¾æ¸é ã®æé ã§ä¸¦ã¹æ¿ããå ´åã¨åãæå³ã«ãªãã¾ãã
# 次ã®äºã¤ã¯åãæå³ @nums = sort @nums; @nums = sort {$a cmp $b} @nums;
è¤æ°æ¡ä»¶ã§ã®ä¸¦ã³æ¿ã
ãæååã®é·ããé·ãé ã§ä¸¦ã³æ¿ãã¦ãé·ããåãã¨ãã¯è¾æ¸é ã®æé ã§ä¸¦ã¹æ¿ããããã«ãã¦ã¿ã¾ãããµãã¤ç®ã®æ¡ä»¶ãæå®ããã¨ãã¯||ã使ç¨ãã¾ããæåã®æ¯è¼ã§ä¸¦ã³é ã確å®ã§ããªãã£ãå ´åã«æ¬¡ã®æ¯è¼ãè¡ããã¾ãã@strsã¯('aaa', 'bbb', 'aa', 'bb', 'a', 'b')ã«ãªãã¾ãã
my @strs = ('aaa', 'bbb', 'b', 'a', 'aa', 'bb'); @strs = sort { length $b <=> length $a || $a cmp $b } @strs;
ããã·ã¥ã®å¤ããã¼ã§ä¸¦ã¹æ¿ãã¦åºå
ãããã·ã¥ããã¼ã§ä¸¦ã¹æ¿ãã¦åºåãã¦ã¿ã¾ããããã·ã¥ã¯ãã¼ã®é åºãä¿éãããªãã®ã§ã決ã¾ã£ã並ã³é ã§åºåãããå ´åã¯ãã¼ã並ã³æ¿ãã¦åºåãã¾ãã
my %points = (Tom => 100, Mike => 30, Mami => 90); for my $name (sort keys %points) { print "$name:$points{$name}\n"; }
é åã®ãªãã¡ã¬ã³ã¹ã®ä¸¦ã¹æ¿ã
ãé åã®ãªãã¡ã¬ã³ã¹ã並ã¹æ¿ãã¦ã¿ã¾ããsorté¢æ°ã«æ¸¡ãã¨ãã«ããªãã¡ã¬ã³ã¹ãã¦ãåãåãã¨ããããªãã¡ã¬ã³ã¹ããã®ããã¤ã³ãã§ãã
my $nums = [5, 11, 3, 2]; @$nums = sort @$nums;
ããã·ã¥ã®é åã並ã¹æ¿ãã
ãããã·ã¥ã®é åã並ã¹æ¿ãã¦ã¿ã¾ãããµã³ãã«ã®ããã·ã¥ã®é åã«ã¯è¤æ°ã®äººã®æ å ±ãå ¥ã£ã¦ãã¾ããããã人ç©ã®å¹´é½¢ã§ä¸¦ã¹æ¿ãã¦ã¿ã¾ãã(注æ: ããã·ã¥ã®é åã¨å¼ãã§ãã¾ããããã§ã®æ£ç¢ºãªæå³ã¯ããã·ã¥ã®ãªãã¡ã¬ã³ã¹ãå«ãé åã®ãªãã¡ã¬ã³ã¹ã®ãã¨ã§ãã)
ã$aã¨$bã«ã¯ããã·ã¥ã®ãªãã¡ã¬ã³ã¹ãä»£å ¥ããã¦ããã®ã§ãå¹´é½¢ãåå¾ããã«ã¯$a->{age}, $b->{age}ã¨ãã¾ããããã使ç¨ãã¦æ¯è¼ãè¡ãã¾ãã
# 人ç©ã®ãã¼ã¿ my $persons = [ {name => 'Ken', age => 19}, {name => 'Taro', age => 9}, {name => 'Kaori', age => 23} ]; @$persons = sort { $a->{age} <=> $b->{age} } @$persons;
ã$personsã¯å¹´é½¢ã®æé ã§ä¸¦ã¹æ¿ãããã¦æ¬¡ã®ãããªãã¼ã¿ã«ãªãã¾ãã
[ {name => 'Taro', age => 9}, {name => 'Ken', age => 19}, {name => 'Kaori', age => 23} ];