简体   繁体   English

Perl在参数中找到奇数

[英]perl find odd odd number in argument

Example: 例:

./odd.pl a a b b b

output: 输出:

b b b

find a odd number argument and print 找到一个奇数参数并打印

I tried: 我试过了:

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

print "\n";

It looks like you want to print the values that appear an odd number of times. 您似乎要打印出现奇数次的值。

The problem with your attempt is that you check the counts before you finish obtaining the count of the different values! 尝试的问题是您在完成获取不同值的计数之前检查计数!

Solution: 解:

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");

Note that I changed eq to == because eq is for string comparisons. 请注意,我将eq更改为==因为eq用于字符串比较。

Simplified solution: 简化解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM