加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 21:52:26 所属栏目:大数据 来源:网络整理
导读:my $line = "file1.gz file2.gz file3.gz";my @abc = split('',$line);print "@abcn"; 预期产量: file1.gzfile2.gzfile3.gz 我希望输出为$abc [0]中的file1.gz,$abc [1]中的file2.gz和$abc [2]中的file3.gz.我该如何拆分$line? 解决方法 按空格拆分字符串
my $line = "file1.gz file2.gz file3.gz";
my @abc = split('',$line);
print "@abcn";

预期产量:

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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读