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

No problem, just store more than one value per hash key. This is known as a HoA.
my %cat2s_by_cat1; while (<$fh2>) { chomp; my ($cat1, $cat2) = split /=/; push @{ $cat2s_by_cat1{$cat1} }, $cat2; } while (<$fh1>) { chomp; my ($dog, $bird, $cat1) = split /=/; exists( $cat2s_by_cat1{$cat1} ) or die; for my $cat2 ( @{ $cat2s_by_cat1{$cat1} } ) { print $fh_out (join('=', $dog, $bird, $cat1, $cat2), "\n"); } }

Replies are listed 'Best First'.
Re^4: Help needed please: Data Manipulation in 2D Array
by Syntenty (Initiate) on May 05, 2008 at 06:53 UTC

    Thanks for your help. I was not aware of the multiple value per hash key. I forgot to mention in my original post that while file 2's data format will always have only 2 elements, FILE one will change.

    It will not always have the same number of elements, or three in this case. How can I change the second part of your code, concerning file handle 1 to account for this? And also I'm not sure how to use your method to output my final data to a file

      I was not aware of the multiple value per hash key.

      Technically, there's only one: A reference to an array. Just like for AoAs. References are scalars, so they can be stored in arrays and hashes.

      It will not always have the same number of elements

      Which one is the cat?

      I'm not sure how to use your method to output my final data to a file

      It already does. The output is written to the $fh_out. I skipped over opening the file handle, but there's nothing special to it:

      my $file_out = 'data.out'; open(my $fh_out, '>', $file_out) or die("Unable to create output file $file_out: $!\n");

        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 ...