微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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:
+?*?{}???

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐