7

我有以下代码。isSubset没有附加的 CPAN 模块可以写得更简单吗?

my @possibleNames = ("adam", "chelsea");
my @actualNames = ("adam", "chucky", "chelsea");

sub isSubset {
    my ($littleSet, $bigSet) = @_;
    foreach (@{$littleSet}) {
        return 0 unless ($_ ~~ @{$bigSet});
    }
    return 1;
}

printf("%s\n", (isSubset(\@possibleNames, \@actualNames) ? "yes" : "no"));
4

2 回答 2

4

一种相当有效的方法是:

sub isSubset {
    my ($littleSet, $bigSet) = @_;
    my %hash;
    undef @hash{@$littleSet};  # add a hash key for each element of @$littleSet
    delete @hash{@$bigSet};    # remove all keys for elements of @$bigSet
    return !%hash;             # return false if any keys are left in the hash
}
于 2013-06-06T00:08:55.520 回答
3
my @possibleNames = ("adam", "chelsea");
my @actualNames = ("adam", "chucky", "chelsea");

my $is_subset = 0==grep !defined, map { @$_{@actualNames}=(1)x@actualNames; delete @$_{@possibleNames} } {};

但说真的,请使用 Array::Utils::array_minus。

于 2013-06-05T19:04:42.900 回答