split使用问题

split使用问题

代码如下:

$P_MESSAGE="a|";
my $P_DELIMITER="|";
my @P_MESSAGE_LINE=split /$P_DELIMITER/, $P_MESSAGE;
print "Num:",scalar @P_MESSAGE_LINE," @P_MESSAGE_LINE\n";

$P_MESSAGE="a,";
my $P_DELIMITER=",";
my @P_MESSAGE_LINE=split /$P_DELIMITER/, $P_MESSAGE;
print "Num:",scalar @P_MESSAGE_LINE," @P_MESSAGE_LINE\n";

$P_MESSAGE="a\n";
my $P_DELIMITER="\n";
my @P_MESSAGE_LINE=split /$P_DELIMITER/, $P_MESSAGE;
print "Num:",scalar @P_MESSAGE_LINE," @P_MESSAGE_LINE\n";

结果如下:

Num:2 a |
Num:1 a
Num:1 a

为什么逗号和换行符不能被拆分,而"|"可以呢?
我测试的结果是
$P_MESSAGE="a,b";
就可以...
a\nb也可以..

所以应该是因为後面是空的...切割出来的array, @ary[1] = "";
对Perl来说认为那个element 是空的...所以不计算...
恩,明白了。谢谢
|可以因为它本身在regex里面就是有特殊含义的

[Copy to clipboard] [ - ]
CODE:
my $message = "abcdef";
my $delimiter = "|";
my @array = split /$delimiter/,$message;
print "$_\n" foreach @array;

这其实相当于

[Copy to clipboard] [ - ]
CODE:
my @array = split//,$message;

而//就相当于切割每一个字符,所以
运行之后的结果为

QUOTE:
a
b
c
d
e
f

如果你把|进行back space,结果就和其他两组一样了

[Copy to clipboard] [ - ]
CODE:
my @array = split /\Q$delimiter\E/,$message;

至于为什么只返回一个,二楼已经解释的很清楚了