Get all corresponding keys for repeated elements
I have a file which consists of 开发者_JS百科following:
A 1 A 2 B 3 B 4 B 5 B 6 C 7 A 8
I want to get all unique keys in first column, but get all corresponding values for that unique key, i.e I need to get:
A 1,2,8 B 3,4,5,6 C 7
What would be the best way to do this?
(I've heard that Perl has good support to solve this, but I'm new to Perl.)try this:
open my $fh, '<', "data_filename";
my %map;
while(my $line = <$fh>) {
my ($key, $val) = split(/\s+/, $line);
push @{$map{$key}}, $val;
}
You probably want a hash, where each value in the hash is an array reference.
my %values;
while (<>) {
my ($left, $right) = split(/ /,$_,2);
my $array = $values{$left};
if (!$array) {
$array = [];
$values{$left} = $array;
}
push(@{$array},$right);
}
You can verify that this has produced the correct data structure with Data::Dumper:
use Data::Dumper;
print Dumper(\%values);
This is just another possible solution for the sake of completeness. In this case, the hash stores a the key and a string containing your values.
use warnings;
use strict;
my %hash = ();
open (FILE, "input.txt") or die "";
while(FILE>){
chomp;
(my $key, my $value) = split;
$value = ",".$value if exists $hash{$key};
$hash{$key}.= $value;
}
foreach my $key (sort keys %hash){
print "$key $hash{$key}\n";
}
As always, there's more than one way to do it.
精彩评论