Perl 字符串操作 以及 自定义排序

#!/usr/bin/perl -w
#########################################################################
# File Name: test6.pl
# Author: kevin xiang
# Created Time: 2014年07月10日 星期四 09时46分37秒
#########################################################################

#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








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值