我正在尝试解析 CSV 文件以读取所有其他邮政编码。我正在尝试创建一个散列,其中每个键都是一个邮政编码,值是它在文件中出现的数字。然后我想将内容打印为邮政编码 - 数字。这是我目前拥有的 Perl 脚本。
use strict;
use warnings;
my %hash = qw (
zipcode count
);
my $file = $ARGV[0] or die "Need CSV file on command line \n";
open(my $data, '<', $file) or die "Could not open '$file $!\n";
while (my $line = <$data>) {
chomp $line;
my @fields = split "," , $line;
if (exists($hash{$fields[2]})) {
$hash{$fields[1]}++;
}else {
$hash{$fields[1]} = 1;
}
}
my $key;
my $value;
while (($key, $value) = each(%hash)) {
print "$key - $value\n";
}
exit;
最佳答案
您没有说明您的邮政编码在哪一列,但是您正在使用第三个字段来检查现有的散列元素,然后使用第二个字段来递增它。
不需要检查散列元素是否已经存在:Perl 会愉快地创建一个不存在的散列元素,并在您第一次访问它时将其递增到 1。
也不需要显式打开作为命令行参数传递的任何文件:如果您使用 <>
,Perl 将打开并读取它们没有文件句柄的运算符。
您自己的程序的这种修改可能会奏效。它假定邮政编码位于 CSV 的第二列中。如果是其他任何地方,只需更改 ++$hash{$fields[1]}
适本地。
use strict;
use warnings;
@ARGV or die "Need CSV file on command line \n";
my %counts;
while (my $line = <>) {
chomp $line;
my @fields = split /,/, $line;
++$counts{$fields[1]};
}
while (my ($key, $value) = each %counts) {
print "$key - $value\n";
}
关于perl - 解析 CSV 文件和散列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16628373/