首页 > 解决方案 > perl 在参数中找到奇数

问题描述

例子:

./odd.pl a a b b b

输出:

b b b

找到一个奇数参数并打印

我试过了:

my %count;
foreach $arg (@ARGV) {
    $count{$arg}++;
    if ($count{$arg} % 2 eq 1) { print "$arg"; }
}

print "\n";

标签: perl

解决方案


看起来您想要打印出现奇数次的值。

您尝试的问题是您在完成获得不同值的计数之前检查计数!

解决方案:

my %counts;
for my $arg (@ARGV) {
    ++$counts{$arg};
}

my @matches;
for my $arg (@ARGV) {
    if ($counts{$arg} % 2 == 1) {
        push @matches, $arg;
    }
}

print("@matches\n");

请注意,我更改eq==因为eq是用于字符串比较。

简化解决方案:

my %counts;
++$counts{$_} for @ARGV;
my @matches = grep { $counts{$_} % 2 } @ARGV;
print("@matches\n");

推荐阅读