in reply to Re: combining 2 files with a comon field
in thread combining 2 files with a comon field

I tried a variation of your suggestion, with an added print debug line:
use strict; use warnings; open FILE1, '<', 'file1' or die ($!); my %file1 = map { split '\|', $_ } <FILE1>; ## we now have A1=>'dog' in hash close FILE1; for(sort keys %file1){ print "$_\n"; print join('|',$_,$file1{$_}),'|',"\n"; }
and got:
Odd number of elements in hash assignment at combine2.pl line 6, <FILE1> line 3.
Use of uninitialized value in join or string at combine2.pl line 13.

||
A1
A1|dog|
A3
A3|bird|
cat
cat|
|

file1 is:
A1|dog|
A2|cat|
A3|bird|

Replies are listed 'Best First'.
Re^3: combining 2 files with a comon field
by radiantmatrix (Parson) on May 18, 2005 at 20:42 UTC

    Well, I did say it was untested. ;-)

    # my %file1 = map { split '\|', $_ } <FILE1>; my %file1 = map { chomp && s/\|$//g && split '\|', $_, 2 } <FILE1>;
    Do make the same changes to the %file2 hash statement, too, in the original code. This clears the | and newline at the end of each file line before splitting, and limits the split to two parts. Hope that helps!

    BTW, this is a good example of how using warnings and strict point out where the bugs are. I knew what the issue was as soon as I saw those two warning statements. ;-) Also, make sure that your file is well-formed: that is, it ends with a newline, or you might get interesting results.

    This should *not* be done in production without some better error control...


    The Eightfold Path: 'use warnings;', 'use strict;', 'use diagnostics;', perltidy, CGI or CGI::Simple, try the CPAN first, big modules and small scripts, test first.

Re^3: combining 2 files with a comon field
by BerniBoy (Acolyte) on May 18, 2005 at 19:43 UTC
    Hmm seems to me like the "map" statement also treats the newline characters after the last "|" character and tries to insert them into the hash somehow.

    Just a guess from what i see here...