我喜欢你的问题。根据您的预期输出,我的解决方案是:
my $string = "C1 and C2 and C3 and C4";
my @split = split / and /, $string;
for my $counter (0..$#split) {
print join ' and ', grep { $_ !~ /$split[$counter]/ } @split;
print "\n";
}
解释:
这里的神奇之处在于grep
只有其中greps
的条目@split
不包含循环当前索引处的部分。例如,我们从 index 开始0
:
# $counter == 0
# $split[$counter] contains C1
# grep goes through @split and only takes the parts of @split
# which does not contain C1, because its inside $split[$counter]
#
# the next loop set $counter to 1
# $split[$counter] contains C2 now and the
# grep just grep again only the stuff of @split which does not contain C2
# that way, we just take the parts of @split which are not at the current loop
# position inside @split :)
编辑:
请注意,我的东西不适用于具有重复条目的字符串:
my $string = "C1 and C2 and C3 and C4 and C4";
输出:
C2 and C3 and C4 and C4
C1 and C3 and C4 and C4
C1 and C2 and C4 and C4
C1 and C2 and C3
C1 and C2 and C3