This will do what you need.
I apologize for the lack of analysis, but it is late and I should be in bed.
I hope this helps.
use strict;
use warnings;
my $fh;
my %switches;
open $fh, '<', 'file1.txt' or die $!;
while (<$fh>) {
my ($origin, @switch) = split;
push @{ $switches{$origin} }, \@switch;
}
open $fh, '<', 'file2.txt' or die $!;
while (<$fh>) {
my ($origin, $freq) = split;
my $switches = join ' ', map join(' ', @$_), @{ $switches{$origin} };
print join(' ', $origin, $freq, $switches), "\n";
}
output
1 0.9 2 0.6 3 0.4
2 0.7 1 0.6 3 0.2
3 0.5 1 0.4
Update
Here is a fixed version of your own code that produces similar results. The main problem is that the values in your %switches
arrays of arrays, so you have to do two dereferences. I've fixed that by adding @switches
, which contains the same contents as the current %switches
value, but has strings in place of two-element arrays.
I've also added use strict
and use warnings
, and declared all your variables properly. The open
calls have been changed to the three-argument open
with lexical file handles as they should be, and they are now being checked for success. I've changed your split
calls, as a simple bare split
with no parameters is all you need. And I've removed your @tmp
and used proper list assignments instead. Oh, and I've changed the wasteful [@array]
to a simple \@array
(which wouldn't have worked without declaring variables using my
).
I still think my version is better, if only because it's much shorter, and yours prints the groups in random order.
#!/usr/bin/perl
use strict;
use warnings;
my ($input1, $input2, $output) = @ARGV;
my %switches;
open my $in1, '<', $input1 or die $!;
while (<$in1>) {
my ($group, @switches) = split;
push @{ $switches{$group} }, \@switches;
}
close $in1;
my %groups;
open my $in2, '<', $input2 or die $!;
while (<$in2>) {
my ($group, $pop) = split;
$groups{$group} = $pop;
}
close $in2;
open my $out, '>', $output or die $!;
for my $group (keys %groups) {
my $pop = $groups{$group};
my @switches = map "@$_", @{ $switches{$group} };
print $out "$group $pop @switches\n"
}
close $out or die $!;