perl - 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";
解决方案
看起来您想要打印出现奇数次的值。
您尝试的问题是您在完成获得不同值的计数之前检查计数!
解决方案:
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");
推荐阅读
- git - 来自现有存储库的 git init new
- php - PHP sftp - 我可以获得下载/上传速度吗?
- python - 如何使用批处理生成器为 python 中的音频信号生成噪声数据?
- javascript - 在 Facebook 等按钮中设置头像图像的样式?
- discord.js - 邀请命令离开 discord.js
- python - 当预测值是连续的而实际值是离散的时,如何找到准确性?
- ios - 当应用程序处于前台时(颤振)在 iOS 中接收 fcm
- python - 当 aiohttp.ClientSession 异步失败时如何重试任务
- winapi - 我需要通过挂钩一些 Windows API 来防止一些黑客修改游戏内存
- python-3.x - AppDynamics 的 Rest API 调用问题