gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 04:59:46 26 4
gpt4 key购买 nike

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

预期输出:
file1.gz
file2.gz
file3.gz

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

最佳答案

按空格拆分字符串非常简单:

print $_, "\n" for split ' ', 'file1.gz file1.gz file3.gz';

这是 split的特殊形式实际上(因为此函数通常采用模式而不是字符串):

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/, $line;
print $_, "\n" for @abc;

关于arrays - 在 Perl 中将字符串拆分为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16872340/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com