while (<TEST>) {
my ($key,@fileData) = split /\|/;
chomp @fileData;
$test{$key} = \@fileData;
}
#to
while (<TEST>) {
chomp;
my ($key,@fileData) = split /\|/;
$test{$key} = \@fileData;
}
Otherwise you are chomping every item in the array, when
you know there can only be a newline at the end of the line.
I would change
foreach my $key (keys %test) {
push (@sorted, "$key|$test{$key}->[0]|$test{$key}->[1]|$test{$ke
+y}->[2]|$test{$key}->[3]");
}
#to
foreach my $key (keys %test) {
push @sorted, (join '|', ($key,@{$test{$key}});
}
except that that is overkill... since you can't have the
multiples of the same key, you don't need to sort on the whole line, just the key, I would do...
open(TEST, ">test.txt") || die "File couldn't be opened for writing: $
+!";
foreach my $key (sort keys %test) {
print TEST (join '|', ($key,@{$test{$key}});
print TEST "\n";
}
close(TEST);
Instead of the whole @sorted thing
Update Sorry, you wanted to sort by the last item in the array of data...
change
foreach my $key (sort keys %test) {
#to
foreach my $key (sort { $test{$a}[-1] <=> $test{$b}[-1] } keys %test)
+{
the $test{$a}[-1] <=> $test{$b}[-1] sorts numerically based on the final item in the data array at each key
Untested, but I believe it all works fine
- Ant |