G'day kris1511,
Your text has "leg_length sorted", but your code has "#SORT BY STR_LEN", so it's unclear exactly which you want. I've used stride length for sorting, but output both lengths, in the example code below.
See the sort function for an explanation, and lots of examples, of how to sort in Perl.
Note that you sort numbers using '<=>' and strings using 'cmp'. I mention this specifically because you're defaulting numeric values to the string "NA"; this will likely cause problems when sorting.
See my earlier post to you, "Re: Multiple File handling and merging records from 2 files", where I described Text::CSV and other elements of my example code below.
The basic sort code you'll want will look something like this:
... sort { $data{$a}{stride_length} <=> $data{$b}{stride_length} } ...
Here's that in an example script.
#!/usr/bin/env perl -l use strict; use warnings; use Text::CSV; use Inline::Files; my %data; my $csv = Text::CSV::->new; while (my $row = $csv->getline(\*FILE1)) { $data{$row->[0]}{stride_length} = $row->[1]; } while (my $row = $csv->getline(\*FILE2)) { @{$data{$row->[0]}}{qw{leg_length diet}} = @$row[1,2]; } print "$_ @{$data{$_}}{qw{stride_length leg_length}}" for sort { $data{$a}{stride_length} <=> $data{$b}{stride_length} } grep { $data{$_}{diet} eq 'herbivore' } map { $data{$_}{diet} ||= 'NA'; $data{$_}{stride_length} ||= 0; $data{$_}{leg_length} ||= 0; $_; } keys %data; __FILE1__ Euoplocephalus,1.87,quadrupedal Stegosaurus,1.90,quadrupedal Tyrannosaurus Rex,5.76,bipedal Hadrosaurus,1.4,bipedal Deinonychus,1.21,bipedal Struthiomimus,1.34,bipedal Velociraptor,2.72,bipedal __FILE2__ Hadrosaurus,1.2,herbivore Struthiomimus,0.92,omnivore Velociraptor,1.0,carnivore Triceratops,0.87,herbivore Euoplocephalus,1.6,herbivore Stegosaurus,1.40,herbivore Tyrannosaurus Rex,2.5,carnivore
Output:
Triceratops 0 0.87 Hadrosaurus 1.4 1.2 Euoplocephalus 1.87 1.6 Stegosaurus 1.90 1.40
— Ken
In reply to Re: Merging 2 Hashes finding result sorted by one of the fields
by kcott
in thread Merging 2 Hashes finding result sorted by one of the fields
by kris1511
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |