文章来源与:http://perlmaven.com/perl-split?翻译:扬眉剑(GRC)rongchaogao@gmail.com
Table of Contents
- 1 一个简单的例子
- 2 限制分成几分
- 3 通过split给标量赋值
- 4 用更复杂的正则分割
- 5 按照多种字符分割
- 6 分割字符
1?一个简单的例子
1: use Data::Dumper; 2: my $str = "ab cd ef gh ij"; 3: my @word = split/s+/,$str; 4: print Dumper(@word);
结果:
1: $VAR1 = [ 2: 'ab',3: 'cd',4: 'ef',5: 'gh',6: 'ij' 7: ]; 8:
2?限制分成几分
1: use Data::Dumper; 2: my $str = "ab cd ef gh ij"; 3: my @word = split/s+/,$str,2; 4: #添加一个参数2,这里整个字符串就被从前往后分成了两部分 5: print Dumper(@word); 6: =结果 7: $VAR1 = [ 8: 'ab', 9: 'cd ef gh ij' 10: ]; 11: =cut 12: use Data::Dumper; 13: my $str = "ab cd ef gh ij"; 14: my @word = split/s+/,3; 15: print Dumper(@word); 16: =结果 17: $VAR1 = [ 18: 'ab',19: 'cd',20: 'ef gh ij' 21: ]; 22: =cut
3?通过split给标量赋值
- 方法一:
1: my $str = "ab cd ef gh ij"; 2: my ($first,$second,$third,$four,$five) = split/s+/,$str; 3: print "first $firstnsecond $secondnthird $thirdnfour $fournfive $fiven"; 4: 5: =结果 6: first ab 7: second cd 8: third ef 9: four gh 10: five ij
- 方法二:
上面的程序可以达到我们的需求,但是,如果我们只需要其中的2个值。那么上面的程序就很繁琐了。 我们可以用下面改进的办法;
1: my $str = "ab cd ef gh ij"; 2: my @word=split/s+/,$str; 3: my $third=@word[2]; 4: my $five =@word[4]; 5: print "third $thirdnfive $fiven"; 6: 7: =结果 8: third ef 9: five ij 10:
- 方法三:
上面的方法也成功的实现了我们的需求,但还是不够简洁,我们还可以通过下面的方法:
1: my $str = "ab cd ef gh ij"; 2: my ($third,$five)=(split/s+/,$str)[2,4]; 3: print "third $thirdnfive $fiven"; 4: =结果 5: third ef 6: five ij
4?用更复杂的正则分割
首先还是一个简单的例子;
1: use Data::Dumper; 2: my $str="fname = Foolname = Baremail=foo@bar.com"; 3: my @array=split/=/,$str; 4: print Dumper(@array); 5: 6: =结果 7: $VAR1 = [ 8: 'fname ', 9: ' Foolname ',10: ' Baremail',11: 'foo.com' 12: ];
上面的结果有什么不妥的地方呢?我们发现分成的四部分中有空格的存在,而空格未必是我们想要的。 所以我们要对程序进行改进
1: use Data::Dumper; 2: my $str="fname = Foolname = Baremail=foo@bar.com"; 3: my @array=split/s*=s*/,$str; 4: print Dumper(@array); 5: 6: =结果 7: $VAR1 = [ 8: 'fname', 9: 'Foolname',10: 'Baremail',11: 'foo.com' 12: ];
我们还可以这样控制
1: use Data::Dumper; 2: my $str="fname = Foolname = Baremail=foo@bar.com"; 3: my @array=split/s+=s+/,$str; 4: print Dumper(@array); 5: =结果 6: $VAR1 = [ 7: 'fname', 8: 'Foolname', 9: 'Baremail=foo.com' 10: ];
上面的字符串$str有3个等号,我们最后的结果却只分成了三分。因为我们在分割的时候, 要求必须=两侧有空格的才进行分割。所以最后的一个等号两侧没有被分割。
5?按照多种字符分割
我们有这么一个字符串"fname=Foo&lname=Bar&email=foo@bar.com"我们既想用“=”分割,也想 用“&”分割。怎么做到呢?
1: use Data::Dumper; 2: my $str = 'fname=Foo&lname=Bar&email=foo@bar.com'; 3: my @user = split /[=&]/,$str; 4: print Dumper (@user); 5: =结果 6: $VAR1 = [ 7: 'fname', 8: 'Foo', 9: 'lname',10: 'Bar',11: 'email',12: 'foo@bar.com' 13: ];
6?分割字符
也许我们有时候还会有这样的要求“hello world”把这个字符串按照字符来分割,分割成"h""e""l" 等等。
1: use Data::Dumper; 2: my $str = "Hello World"; 3: my @chars = split //,$str; 4: print Dumper(@chars); 5: 6: =结果 7: $VAR1 = [ 8: 'H', 9: 'e',10: 'l',11: 'l',12: 'o',13: ' ',14: 'W',15: 'o',16: 'r',17: 'l',18: 'd' 19: ];
注意这里是用//来分割的。要和省略分割符号区别开,如果省略分割符号,默认用空格分割。