你實際上是不匹配任何東西。我將調試輸出添加到您的代碼中。
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::MoreUtilsuniq
。
my @unique = uniq @list;
如果你想知道每個元素,如果它是任何其他元素的子串,你可以使用Perl's builtin index
,它發現某個字符串在另一字符串中的位置,以及grep
。
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都是「1」。請注意,如果根本沒有匹配,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;
你是否只是「一」被報告爲愚蠢?例如。不是子字符串匹配? – Sobrique