Re: [问题] Perl split/join 问题

楼主: gugod (å•Š)   2018-03-03 19:00:40
如果用 Data::Dumper 来观察 @a 的内容,就可以发现其实里面只有两项:
use Data::Dumper 'Dumper';
my @a = split /,/, ',2,';
say Dumper(\@a);
输出:
$VAR1 = [
'',
'2'
];
所以其实 join(',',@a) 本身的行为是正确的。
而这个 split 的行为则有写在文件 perldoc -f split 当中:如果尾巴的内
容是空的,就会被截掉。如果要保留空白,就在第三个参数位置上放个负数:
my @a = split /,/, ',2,', -1;
文件:https://perldoc.perl.org/functions/split.html
以下引用文件内文相关的两段:
If LIMIT is negative, it is treated as if it were instead
arbitrarily large; as many fields as possible are produced.
If LIMIT is omitted (or, equivalently, zero), then it is usually
treated as if it were instead negative but with the exception that
trailing empty fields are stripped (empty leading fields are always
preserved); if all fields are empty, then all fields are considered to
be trailing (and are thus stripped in this case). Thus, the following:
print join(':', split(/,/, 'a,b,c,,,')), "\n";
produces the output a:b:c , but the following:
print join(':', split(/,/, 'a,b,c,,,', -1)), "\n";
produces the output a:b:c::: .
我猜测这行为多半是某种字串处理的优化。
作者: gecer (gecer)   2018-03-04 11:14:00
只能推了~~

Links booklink

Contact Us: admin [ a t ] ucptt.com