in reply to Re^5: Help needed please: Data Manipulation in 2D Array
in thread Help needed please: Data Manipulation in 2D Array


File handle one will be variable in elements.

For example in one file input it could be

goat1=dog1=bird1=cat1
or
tiger2=goat2=dog2=bird2=cat2

Because of this
   my ($dog, $bird, $cat1) = split /=/;

will be a problem since in this case the code assumes there will always be $dog, $bird, $cat, while there could be more.


The last element however, will always be "cat" while the ones before will change.

File 2 will remain the same even though file 1 can change.
File 2 is
cat1=cat3
cat3=cat4 ...

Replies are listed 'Best First'.
Re^7: Help needed please: Data Manipulation in 2D Array
by ikegami (Patriarch) on May 05, 2008 at 08:08 UTC
    Variable length ordered list? Array!
    use strict; use warnings; my $file_in1 = '...'; my $file_in2 = '...'; my $file_out = '...'; open(my $fh_in1, '<', $file_in1) or die("Unable to open input file $file_in1: $!\n"); open(my $fh_in2, '<', $file_in2) or die("Unable to open input file $file_in2: $!\n"); open(my $fh_out, '>', $file_out) or die("Unable to create output file $file_out: $!\n"); my %cat2s_by_cat1; while (<$fh_in2>) { chomp; my ($cat1, $cat2) = split /=/; push @{ $cat2s_by_cat1{$cat1} }, $cat2; } while (<$fh_in1>) { chomp; my @fields = split /=/; my $cat1 = $fields[-1]; exists( $cat2s_by_cat1{$cat1} ) or die("Cat1 $cat1 not found in file2\n"); for my $cat2 ( @{ $cat2s_by_cat1{$cat1} } ) { print $fh_out (join('=', @fields, $cat2), "\n"); } }

      The code works! You are amazing! Thank you so much!