Re: concatenating multiple matches?

Re: concatenating multiple matches?

am 17.12.2007 23:47:00 von krahnj

nun wrote:
>
> I have a script which loads the contents of two tab-delimited text files
> into two hashes of arrays.
>
> Text file 1 contains only unique SKUs.
> This data is read into a hash of arrays named HoA1.
> Example lines from text file 1:
> SKU1 CORNDOGS
> SKU2 FISHSTICKS
>
> Text file 2 may contain multiple lines with the same SKU.
> This data is read into a hash of arrays named HoA2.
> Example lines from text file 2:
> SKU1 BREADED
> SKU1 BEEF
> SKU1 STICK
> SKU2 BREADED
> SKU2 FISH
>
> The script goes through HoA1 and looks for matching SKUs from HoA2. If a
> match is found, the additional data is appended to the description like
> this:
>
> foreach my $j (sort (keys %HoA)1) {
>
> $my $DESCRIPTION=$HoA1{$j}[1];
>
> if($HoA_2{$j}) {
> $DESCRIPTION=$DESCRIPTION." More Info:".$HoA_{$j}[1];
> }
>
> print "$SKU\t$DESCRIPTION\n";
>
> }
>
> This works ok, but only seems to add the info from the last matching
> line form the second text file's data. Example output would be:
>
> SKU1 CORNDOGS More Info: STICK
>
> I need instead to see:
>
> SKU1 CORNDOGS More Info: BREADED, BEEF, STICK
>
> Is there a simple way to modify my code to do this, or is a conceptual
> overhaul required? Any hints would be welcomed.

This should work:

#!/usr/bin/perl
use warnings;
use strict;

my $file_1 = 'file_1';
my $file_2 = 'file_2';

open my $fh, '<', $file_2 or die "Cannot open '$file_2' $!";

my %data;
while ( <$fh> ) {
chomp;
my ( $key, $value ) = split /\t/;
push @{ $data{ $key } }, $value;
}

close $fh;

open $fh, '<', $file_1 or die "Cannot open '$file_1' $!";

while ( <$fh> ) {
chomp;
my ( $key, $value ) = split /\t/;
if ( exists $data{ $key } ) {
print "$key\t$value More Info: ", join( ', ', @{ $data{ $key } }
), "\n";
}
}

__END__



John
--
use Perl;
program
fulfillment