perl split 的一种特殊用法

时间:2024-11-02 23:06:25

参考 http://blog.chinaunix.net/uid-1919528-id-2792055.html

split 函数的正规语法应该是:

split /PATTERN/, EXPR

而使用单引号(或者双引号)来分隔空格(whitespace)是一种特殊的例子:

As a special case, if the expression is a single space (" "), the function splits on
whitespace just as split with no arguments does. Thus, split(" ") can be used to
emulate awk ’s default behavior. In contrast, split(/ /) will give you as many null
initial fields as there are leading spaces. (Other than this special case, if you supply
a string instead of a regular expression, it’ll be interpreted as a regular expression
anyway.) -- Programming Perl
#!/usr/bin/perl -w

use strict;

my $test = "the  first gap has two whitespace";
$_ = $test; my $first = (split)[1];
my $second = (split(" ", $test))[1];
my $third = (split(/ /, $test))[1]; # 贪婪匹配,匹配尽量多的空格 print "\$first is $first\n"; # $first is first
print "\$second is $second\n"; # $second is first
print "\$third is $third\n"; # $third is