Perl Learning - 16 (split, join, list m//, +? *? {}? ??)

split can create list from given string,the format is:
@fields=split /separtor/,$string;
 
The 'separtor' usually are : or space,and it can be any other charactar/symbol.
 
@fields=split /:/,":abc:def::g:h::";
foreach(@fields){
 print "$_\n";
}
 
By default split keeps the 'undef(s)' at the beginning and drops those at the end,into a list.
To keep those at the end,use -1 as the last argument of split.
 
@fields=split /:/,":abc:def::g:h::",-1;
foreach(@fields){
 print "$_\n";
}
 
split defaultly handle $_ if no string provided:
 
$_="  This   is a \t    test.\n";
my @args=split /\s+/;
foreach(@args){
 print "$_\n";
}
 
If non patten is provided,it takes /\s+/ by default,so the same as blow:
 
$_="  This   is a \t    test.\n";
my @args=split;
foreach(@args){
 print "$_\n";
}
 
join do the oppsite thing from split,it join elements of list into a string.
Format: $string=join $glue,@pieces;
 
my $x=join ":",4,6,8,10,12;
print "$x\n";
 
If the list has only one element,join does nothing; join a empty list gets an empty.
 
my $y=join " foo ","bar";
print "$y\n";
my @empty;
my $empty=join "baz",@empty;
print "$empty\n";
 
We can split a string into pieces and them join them with other glues:
 
my @values=split /:/,$x;
my $z=join "-",@values;
 
Note split gets a list,join gets a string; join use character as glue,but not /patten/
 
m// in list context returns the matches list.
 
$_="Hello there,neighbor!";
my ($first,$second,$third)=/(\S+) (\S+),(\S+)/;
print "$second is my $third\n";
 
/i /g /s can also be used.
 
my $text="Fred dropped a 5 ton granite block on Mr. Slate";
my @words=($text=~/[a-z]+/ig);
print "Result: @words\n";
#Result: Fred dropped a ton granite block on Mr slate
 
By default,* + {m,n} are all greedy,which tries to match as much as it can.
We can use their non-greedy mod to just match the least characters.
 
$_="fred and barney went bowling last night,barney won";
if(/(?<names>fred.+barney)/){
 print "$+{names}\n";
 # fred and barney went bowling last night,barney
}
 
$_="fred and barney went bowling last night,barney won";
if(/(?<names>fred.+?barney)/){
 print "$+{names}\n";
 fred and barney
}
 
The greedy + works like this:
When it matches fred,going to .+ it eats all the rest of characters except \n at the end. It searches barney from the end,character by character,if not found it throws out one character then search again; if found then match the whole patten,returns.
 
The non-greedy +? works like this:
When it matches fred,going to .+? it eats the next one character and search barney,if not match eats one more character and search again,until it matches barney it stops eating and returns.
All the non-greedy guys are:
+?*?{}???

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...