First off, your files are backwards, there are spaces in the data segments, and it always makes sense to keep the key as part of the data. That said
Notice use of a subroutine to read both files, passing a pointer to %app_map, listing the key by name, and listing the names of the cols. Also notice cleaning the blanks from the beginning and the end of the values, only storing the data if it exists ('NA" is a "defined" value), and building a new subhash or repopulating an existing subhash. Also notice the use of $v as the subhash in the testing phase.use strict; use warnings; use Data::Dumper; my %app_map; readit (\%app_map,'2.csv','name',qw /name leg_len diet/); readit (\%app_map,'1.csv','name',qw /name str_len stance/); my @result; while ( my ($k, $v) = each %app_map ) { if(defined($v->{diet}) && $v->{diet} eq 'herbivore' && defined($v->{str_len}) ){ push @result,$v;} } my @sorted=sort {$a->{str_len} <=> $b->{leg_len}} @result; for my $row (@sorted) { print $row->{name}.' '.$row->{leg_len}."\n"; } #print Dumper \%app_map; exit; sub readit { my $db=shift; my $fn=shift; my $key=shift; my @vars=@_; open my $fh, '<', $fn or die $!; my $header1 = <$fh>; my $vn=$#vars; while(my $row = <$fh>){ chomp $row; my $h0={}; my @parts= split /\,/, $row; for my $ii (0..$vn){ unless (defined ($parts[$ii])) {$parts[$ii]='';} $parts[$ii]=~s/^\s+//; $parts[$ii]=~s/\s+$//; unless ($parts[$ii] eq '') { $h0->{$vars[$ii]}=$parts[$ii]; + } } my $keyval=$h0->{$key}; my $h1=$db->{$keyval}; unless ($h1) { $db->{$keyval}=$h0; } else { while ( my ($k, $v) = each %$h0 ) {$h1->{$k}=$v;} } # exists } # row close $fh or die $!; } # readit
Hadrosaurus 1.4 Euoplocephalus 1.87 Stegosaurus 1.90
If you turn this in as your homework assignment the teacher will know you got someone to do it for you so you better be able to explain EVERTHING. Adding comments to explain will go a long way to not being failed. That task turns this assignment into a learning exercise now.Hadrosaurus 1.2 Stegosaurus 1.40 Euoplocephalus 1.6
In reply to Re: Merging 2 Hashes finding result sorted by one of the fields
by huck
in thread Merging 2 Hashes finding result sorted by one of the fields
by kris1511
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |