我有一个文件,我需要将其读入Perl,找到我姓名和出生年份的所有出生人数,然后找到我姓名和年份出生人数最多和最低的州。我可以做第一部分,但是在尝试按年和DOB找到最高和最低状态时我完全迷失了。我如何匹配并跟踪这个? 这是我到目前为止的代码:
use 5.13.0;
use warnings;
use strict;
my $file;
my $line;
my $count = 0;
my $total;
my $name;
my $year, my $gender;
my $state;
$file = "StateNames.csv";
open( FILE, "$file" );
while ( $line = <FILE> ) {
if ( $line =~ /Paul,1982/ ) {
( $line, $name, $year, $gender, $state, $total ) = split /,/, $line;
$count = $count + $total;
}
}
if ( $count == 0 ) {
print
"There were no people named Paul found. Please try again.";
}
print "The total number of people named Paul born in 1982 is $count";
print $state $total;
文件
406738 Pilar 1964 F CA 8
406739 Piper 1964 F CA 8
406740 Raelynn 1964 F CA 8
406741 Rafaela 1964 F CA 8
406742 Reba 1964 F CA 8
406743 Risa 1964 F CA 8
406744 Robbi 1964 F CA 8
406745 Rolanda 1964 F CA 8
答案 0 :(得分:0)
您希望将数据放在多个哈希中。这将是一个开始:
my %parsedInfo;
my @info;
my $i = 1;
while (defined (my $line = <DATA>)) {
my ($lineNumber, $name, $year, $gender, $state, $total)
= @info = split /\s+/, $line;
push @{$parsedInfo{$name}{$year}{$state}}, [@info];
}
foreach my $name (sort keys %parsedInfo) {
my $yearRef = $parsedInfo{$name};
foreach my $year (sort {$a <=> $b} keys %$yearRef) {
my $stateRef = $yearRef->{$year};
foreach my $state (sort keys %$stateRef) {
print "$name=>$year=>$state ==========\n";
for my $infoRef (@{$parsedInfo{$name}{$year}{$state}}) {
print join(':', @$infoRef), "\n";
}
}
}
}
输出看起来像这样
Pilar=>1964=>CA ==========
406738:Pilar:1964:F:CA:8
Piper=>1964=>CA ==========
406739:Piper:1964:F:CA:8
Raelynn=>1964=>CA ==========
406740:Raelynn:1964:F:CA:8
Rafaela=>1964=>CA ==========
406741:Rafaela:1964:F:CA:8
Reba=>1964=>CA ==========
406742:Reba:1964:F:CA:8
Risa=>1964=>CA ==========
406743:Risa:1964:F:CA:8
Robbi=>1964=>CA ==========
406744:Robbi:1964:F:CA:8
Rolanda=>1964=>CA ==========
406745:Rolanda:1964:F:CA:8
这会创建一个键入名称的哈希,该哈希包含一个键入年份的哈希值,该哈希值包含一个键入包含该条目数据的状态的哈希值。
一旦你有适当的哈希,你可以做任何你想做的事情。将它放在调试器中并逐步完成它以便更好地理解。如果没有更好的数据,我就无法做更多的事情。
希望这会有所帮助...... 史蒂夫S。