【发布时间】:2013-05-13 18:18:30
【问题描述】:
我正在尝试解析 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;
【问题讨论】:
-
你有什么问题?
-
fields[1] 变量似乎存在一些错误。当我运行它时,它说它未初始化。
-
您的样本输入数据是什么样的;匹配的期望输出是什么?数据包含引用字段是否存在危险?如果是这样,引用字段中的逗号怎么样?如果输入数据中有任何怪癖,您可能需要使用Text::CSV。
-
欢迎来到 Stack Overflow。请尽快阅读FAQ。 (我第一次错过了。)你测试
exists($hash{$fields[2]}),然后处理$hash{$fields[1]}++……这就是麻烦吗? -
一行看起来像:511 Marshall Square 44965 Rosemount Connecticut 689-068-3997