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;

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...