你实际上没有匹配任何东西。我在您的代码中添加了调试输出。
my @list = ( "one", "two", "three", "onefour", "one" );
foreach my $f (@list) {
say "f: $f";
my $length = length($f);
say "length: $length";
say "true { $length && $f} $_: " . ( $length && "$f" ) for @list;
my $count = true { $length && "$f" } @list;
say "count: $count";
if ( $count > 1 ) {
print "Error with: ", $f, " counted ", $count, " times!\n";
}
$count = 0;
}
我们来看看:
f: one
length: 3
true { 3 && one} one: one
true { 3 && one} two: one
true { 3 && one} three: one
true { 3 && one} onefour: one
true { 3 && one} one: one
count: 5
Error with: one counted 5 times!
f: two
length: 3
true { 3 && two} one: two
true { 3 && two} two: two
true { 3 && two} three: two
true { 3 && two} onefour: two
true { 3 && two} one: two
count: 5
Error with: two counted 5 times!
f: three
length: 5
true { 5 && three} one: three
true { 5 && three} two: three
true { 5 && three} three: three
true { 5 && three} onefour: three
true { 5 && three} one: three
count: 5
Error with: three counted 5 times!
f: onefour
length: 7
true { 7 && onefour} one: onefour
true { 7 && onefour} two: onefour
true { 7 && onefour} three: onefour
true { 7 && onefour} onefour: onefour
true { 7 && onefour} one: onefour
count: 5
Error with: onefour counted 5 times!
f: one
length: 3
true { 3 && one} one: one
true { 3 && one} two: one
true { 3 && one} three: one
true { 3 && one} onefour: one
true { 3 && one} one: one
count: 5
Error with: one counted 5 times!
所以你总是有字符串$f 的长度,它大于0,因此在Perl 中计算为true。然后你有$f。这也是true,因为所有不是空字符串('')的字符串都是真的。
您使用true 函数遍历@list 中的所有元素。该块始终为真。所以你总能得到@list中元素的数量。
如果你只想去除重复出现的次数,你可以使用哈希来计算它们。
my %count;
$count{$_}++ for @list;
my @unique = keys %count; # unsorted
# see Sobrique's answer with grep for sorted the same way as before
那么List::MoreUtils中还有uniq。
my @unique = uniq @list;
如果你想知道每个元素是否是 any 其他元素的子字符串,你可以使用Perl's builtin index,它可以找到一个字符串在另一个字符串中的位置,以及一个@987654338 @。
foreach my $f (@list) {
if ( my @matches = grep { $_ ne $f && index( $_, $f ) > -1 } @list ) {
warn "$f is a substr of: @matches"; # will auto-join on $,
}
}
__END__
one is a substr of: onefour at /code/scratch.pl line 91.
one is a substr of: onefour at /code/scratch.pl line 91.
当然,由于ne,这并不能说明元素 0 和 4 都是“一”。请注意,如果根本没有匹配项,index 将返回 -1。
编辑在your comment on Sobrique's answer之后:
要仅在存在重复项(或 substr 重复项)时获得警告,只需对它们进行计数。任何地方都没有修改:
my @list = ( "one", "two", "three", "onefour", "one" );
my %count;
$count{$_}++ for @list;
warn sprintf 'Number of duplicates: %d', @list - keys %count if @list != keys %count;
my $count_substr;
foreach my $f (@list) {
$count_substr++
if grep { $_ ne $f && index( $_, $f ) > -1 } @list;
}
warn sprintf 'Number of substring duplicates: %d', $count_substr if $count_substr;