Perl中的sort()函數用於對使用或不使用排序方法的列表進行排序。用戶可以以子例程或塊的形式指定此方法。如果未指定子例程或塊,則它將遵循默認的排序方法。
用法:
sort List
sort block, List
sort Subroutine, List
返回值:根據用戶要求排序列表
示例1:
#!/usr/bin/perl
@array1 = ("a", "d", "h", "e", "b");
print "Original Array: @array1\n";
print ("Sorted Array: ", sort(@array1));
輸出:
Original Array: a d h e b Sorted Array: abdeh
示例2: 使用塊排序
#!/usr/bin/perl -w
use warnings;
use strict;
# Use of Block to sort
my @numeric = sort { $a <=> $b } (2, 11, 54, 6, 35, 87);
print "@numeric\n";
輸出:
2 6 11 35 54 87
在上麵的代碼中,使用block進行排序是因為sort()函數使用字符對字符串進行排序,但是在數字上下文中,不能跟隨它。因此,塊用於簡化排序。
示例3: 使用子例程進行排序
#!/usr/bin/perl -w
use warnings;
use strict;
# Calling subroutine to sort numerical array
my @numerical = sort compare_sort (2, 11, 54, 6, 35, 87);
print "@numerical\n";
# function to compare two numbers
sub compare_sort
{
if($a < $b)
{
return -1;
}
elsif($a == $b)
{
return 0;
}
else
{
return 1;
}
}
輸出:
2 6 11 35 54 87
相關用法
- Perl int()用法及代碼示例
- Perl exp用法及代碼示例
- Perl tell()用法及代碼示例
- Perl uc()用法及代碼示例
- Perl ord()用法及代碼示例
- Perl abs()用法及代碼示例
- Perl oct()用法及代碼示例
- Perl each()用法及代碼示例
- Perl hex用法及代碼示例
- Perl log()用法及代碼示例
- Perl chr()用法及代碼示例
- Perl sin()用法及代碼示例
- Perl cos()用法及代碼示例
- Perl values()用法及代碼示例
- Perl join()用法及代碼示例
注:本文由純淨天空篩選整理自Code_Mech大神的英文原創作品 Perl | sort() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。