您好,登錄后才能下訂單哦!
#!/usr/bin/perl -w
#########################################################################
# File Name: test6.pl
#########################################################################
#index(str,substr,position),在大字符串中查找
#position可以設置起始位置,返回位置數
my $stuff = "hello word";
my $where = index($stuff, "wor");
print "where: $where\n";
my $where1 = index($stuff, "w");
print "where1: $where1\n";
my $where2 = index($stuff, "w", 6);
print "where2: $where2\n";
# substr($string, $init_position, $length) 處理部分字符串
$substr1 = substr("hello world", 6, 5); #得到substr1: world
print "substr1: $substr1\n";
#可以作替換字符串使用
substr($substr1,0,0)="hello ";
print "substr1: $substr1\n"; #substr1: hello world
#替換功能也可以使用第四個參數
$string = "hello world";
substr($string, 0, 5, "xxxxx");
print "string: $string\n";
#sprintf 格式化數據
$year = "2014";
$month = 8;
$day = 2.0;
$data_tag = sprintf("%s/%d/%.3f", $year, $month, $day);
print "data_tag: $data_tag\n"; #data_tag: 2014/8/2.000
#排序
#排序子函數,按數字排序
sub by_num{
$a <=> $b
}
@nums = (1,4,22,5,33,10,12);
print "nums: @nums\n";
@result1 = sort @nums;
print "result1: @result1\n"; #只會把數字當作字符排序
@result2 = sort by_num @nums;
print "result2: @result2\n"; #會根據數值大小進行排序
#對hash排序
my %socre = (
"kevin" => 100,
"xiang" => 50,
"jie" => 150,
"xxx" => 1,
"yyy" => 50
);
@socre1 = %socre;
print "socre1: @socre1\n"; #socre1: xiang 50 jie 150 kevin 100 xxx 1 yyy 50
#排序子函數,根據value 從小到大
#如果是數字直接用 <=> 如果是字符串用 cmp
sub by_socre_value{
$socre{$a} <=> $socre{$b}
}
@socre2 = sort by_socre_value keys %socre;
print "socre2: @socre2\n"; #socre2: xxx xiang yyy kevin jie
%socre = (
"kevin" => 100,
"xiang" => 50,
"jie" => 150,
"xxx" => 1,
"yyy" => 50
);
#根據value 從小到大, 如果value相同,則根據key字母反序
#如果還有很多個條件,可以加or再限制
sub by_socre_value_and_key{
$socre{$a} <=> $socre{$b}
or
$b cmp $a;
}
@socre3 = sort by_socre_value_and_key keys %socre;
print "socre3: @socre3\n"; #socre3: xxx yyy xiang kevin jie
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。