- 在字符串内用index
- my $stuff = 'Howdy world!';
- my $where = index($stuff,'wor');
- print $where; # 6
- my $stuff = 'Howdy world!';
- my $where1 = index($stuff,'w'); #2
- my $where2 = index($stuff,'w',$where1+1); #6
- my $where3 = index($stuff,'w',$where2+1); #-1
- 在字符串内用 rindex 搜所
- my $last_slash = rindex("/etc/password",'/'); #4
- my $fred = 'Yabba dabba doo!';
- my $where1 = rindex($fred,'abba'); #7
- my $where2 = rindex($fred,'abba',$where1-1); #1
- my $where3 = rindex($fred,'abba',$where2-1); #-1
- 用substr处理子串
- $part = substr($string,$initial_position,$length);
- my $mineral = substr('Fred J. Plintstone',8,5); #Plint
- my $rock = substr 'Fred J. Plintstone',13,100; #stone
- my $string = 'Hello, world!';
- substr($string ,0,5) = 'Goodby'; #Goodby, world!
- substr和index 一起使用
- my $long = 'some very very long string';
- my $lin = index($long,'l'); #15
- my $right = substr($long,index($long,'l')); #long string
- mmy $string = 'dkfkkakdfredddddd';
- substr($string,-13) =~ s/fred/barney/g; #dkfkkakdbarneyddddd
- 高级排序
- sub by_number {
- if ($a<$b) {-1} elsif ($a>$b){ 1 } else {0}
- }
- my @some_numbers = qw /3 4 6 1 2 9/; # 3 4 6 1 2 9
- my @result = sort by_number @some_numbers; # 123469
- sub by_number {$a <=> $b}
- my @some_numbers = qw /3 4 6 1 2 9/;
- my @result = sort by_number @some_numbers;
- 按哈希值排序
- my %score = ('bareny' => 195,'fred' => 205,'dino' => 30,'bamm-bamm' => 195);
- my @winners = sort by_score keys %score;
- sub by_score {
- $score{$b} <=> $score{a}
- }
- print "@winners"; #fred bamm-bamm dino bareny
- 哈希值查找Fred
- my $flag = 0;
- foreach my $key(keys %name) {
- next unless $key =~ /Fred/;
- $flag = $key;
- last;
- }