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

arrays – 在Perl中将字符串拆分为数组

my $line = "file1.gz file2.gz file3.gz";
my @abc = split('',$line);
print "@abc\n";

预期产量:

file1.gz
file2.gz
file3.gz

我希望输出为$abc [0]中的file1.gz,$abc [1]中的file2.gz和$abc [2]中的file3.gz.我该如何拆分$line?

解决方法

按空格拆分字符串非常简单:
print $_,"\n" for split ' ','file1.gz file1.gz file3.gz';

这实际上是一种特殊的拆分形式(因为这个函数通常采用模式而不是字符串):

As another special case,split emulates the default behavior of the
command line tool awk when the PATTERN is either omitted or a literal
string composed of a single space character (such as ' ' or "\x20"). In this case,any leading whitespace in EXPR is
removed before splitting occurs,and the PATTERN is instead treated as
if it were /\s+/; in particular,this means that any contiguous
whitespace (not just a single space character) is used as a separator.

这是原始问题的答案(使用一个没有任何空格的简单字符串):

也许你想分开.gz扩展名:

my $line = "file1.gzfile1.gzfile3.gz";
my @abc = split /(?<=\.gz)/,$line;
print $_,"\n" for @abc;

在这里,我使用了(?< = ...)构造,它是look-behind assertion,基本上在前面有.gz子串的行中的每个点处进行分割.

如果使用固定的扩展集,则可以扩展模式以包含所有扩展:

my $line = "file1.gzfile2.txtfile2.gzfile3.xls";
my @exts = ('txt','xls','gz');
my $patt = join '|',map { '(?<=\.' . $_ . ')' } @exts;
my @abc = split /$patt/,"\n" for @abc;

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

相关推荐