end0tknr's kipple - 新web写経開発

http://d.hatena.ne.jp/end0tknr/ から移転します

javascript と perl のそれぞれで、sort関数による並び替え

javascript

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
var LIST_ORG =
 [{name:'tanaka'},
  {name:'suzuki'},
  {name:'ando'}];

function main(){
   var list_new = LIST_ORG;
   LIST_ORG.sort(function (a,b){ return sort_list(a,b) } );

   for (var i=0; i<list_new.length; i++){
     alert( list_new[i].name );
   }
}

function sort_list(a,b){
   if(a.name == b.name){
     return 0;
   }
   if(a.name < b.name){
     return -1;
   }
   return 1;
}
</script>
</head>
<body>
  <button type="button" onClick="main()">SORT LIST</button>
</body>
</html>

perl

#!/usr/local/bin/perl
use strict;

my $LIST_ORG = [{name=>'tanaka'}, {name=>'suzuki'}, {name=>'ando'}];

main();

sub main {

    my $list_new = $LIST_ORG;

    for my $elm (sort {sort_list($a,$b)} @$LIST_ORG ){
        print "$elm->{name}\n";
    }
}

sub sort_list {
    my ($a,$b) =@_;
    return $a->{name} cmp $b->{name};
}