MSN: Phenzer@hotmail.com 欢迎加为好友讨论测试

perl中数组函数详解六:sort和内联函数

上一篇 / 下一篇  2010-11-07 17:24:57 / 个人分类:脚本语言

  下面将介绍对数组进行排序的函数:sort和内联函数
一、sort函数
 1.作用:对数组元素进行排序,并返回排序后的数组
 2.格式
       sort(SUBROUTINE LIST);
       sort (LIST);
 3.实例:#sort
   @words=("tomataes","tomorrow","patatoes","phantom","Tommy");
   @item=sort @words;
   print "1.@words\n";
   print "2.@item\n";
3.1.结果
   1.tomataes tomorrow patatoes phantom Tommy
   2.Tommy patatoes phantom tomataes tomorrow

4.实例
  @words=("tomataes","tomorrow","patatoes","phantom","Tommy");
  print "1.@words\n";

  sub ascii_sort{
      $a cmp $b;
  }

  @ascill=sort(ascii_sort @words);
  print "2.sort by acsii:@ascill\n";
 
  sub num_sort{
     $a<=>$b;
  }

  @num=sort(num_sort 7,4,2,8,10,44);
  print "3.sort by num:@num\n";

4.1结果
  1.tomataes tomorrow patatoes phantom Tommy
  2.sort by acsii:Tommy patatoes phantom tomataes tomorrow
  3.sort by num:2 4 7 8 10 44

5.总结
 (1)如果没有指定SUBROUTINE,sort函数会按照字符串先后顺序排列;若指定了SUBROUTINE,则sort的第一个参数就是排序子例程,第二个参数是待排序的值
 (2)若在子例程中使用cmp运算符,则排序按照ASCII码进行排序。如果使用<=>,则按照数字进行排序。
 (3)待排序的值是通过引用传递给子例程,有$a和$b变量表示,而不是数组@_,所以千万不能修改$a和$b变量
 (4)默认$a和$b变量会按升序处理待排序的值。如果想按降序排,则$a和$b顺序反过来。


二、内联函数

 1.作用:对数组元素进行排序,并返回排序后的数组
 2.格式:sort{SUBROUTINE_implement}(LIST)
 3.实例:
   @num=sort{$a<=>$b}(7,4,2,8,10,44);
   print "1.sort by num:@num\n";

 4.结果
  1.sort by num:2 4 7 8 10 44

 5.总结
  为sort函数提供一个匿名的子例程来实现排序---内联函数


TAG: 实例 应用 SORT sort 排序 内敛

 

评分:0

我来说两句

Open Toolbar