MrChat has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I'm trying to add data from two different text files into a same hash. An example: Text File 1 contains the words Brazil, London, England. Text file 2 contains Brésil, Londres and Angleterre. I would like to be able to store that data into a hash as follows: %Hash (‘Brazil => ‘Brésil’, ‘London’ => ‘Londres’, ‘England’ => ‘Angleterre’) and then print that hash to another text file to get: Brazil = Brésil London = Londres England = Angleterre Does any one know how this can be done? Thanks
  • Comment on adding text from different txt file into hash

Replies are listed 'Best First'.
Re: adding text from different txt file into hash
by Limbic~Region (Chancellor) on Apr 20, 2005 at 15:51 UTC
    MrChat,
    The following code is a starting point. You need to modify it accordingly to your given situation (how to handle files of difference number of lines, duplicates, or preserving order for instance).
    #!/usr/bin/perl use strict; use warnings; open(FILE1, '<', 'file1.txt') or die $!; open(FILE2, '<', 'file2.txt') or die $!; open(FILE3, '>', 'file3.txt') or die $!; my %hash; while ( <FILE1> ) { chomp; my $val = <FILE2>; chomp $val; $hash{ $_ } = $val; } print FILE3 "$_ = $hash{ $_ }\n" for keys %hash;

    Cheers - L~R

Re: adding text from different txt file into hash
by JediWizard (Deacon) on Apr 20, 2005 at 15:52 UTC

    while(<FILE1>){ my $value = <FILE2>; $hash{$_} = $value; } print FILE3 join("\n", map({"$_ = $hash{$_}"} keys %hash));

    That will readu lines from file handle FILE1 and use it as a key, the value being the corresponing line in FILE2. Is it that simple? Is there some more logic I need to know about? Do you really want line1 from file1 to be the key to line1 from file2? If so that above will do it (I left out the actual opening of the files, but I assume you can do that part).

    Update: You should chomp $value, as L~R so astutely points out in his code above.


    A truely compassionate attitude towards other does not change, even if they behave negatively or hurt you

    —His Holiness, The Dalai Lama

      not safe when the files are variable length.
      while(<FILE1>){ my $value = <FILE2>; warn "File lengths different!", last unless defined $value; $hash{$_} = $value; } print FILE3 join("\n", map({"$_ = $hash{$_}"} keys %hash));


      holli, /regexed monk/
Re: adding text from different txt file into hash
by Transient (Hermit) on Apr 20, 2005 at 16:01 UTC
    Very blind and weird-looking:
    open( FILE1, "file1.txt" ) or die "Unable to open file1.txt\n$!\n"; open( FILE2, "file2.txt" ) or die "Unable to open file2.txt\n$!\n"; my %hash; @hash{ map{ chomp; $_ } <FILE1> } = map { chomp; $_; } <FILE2>
    Print to the third file as any of the above.
      similar
      use File::Slurp; my %h; @h{map{chomp;$_}read_file("test1.txt")}=(map{chomp;$_}read_file("test2 +.txt"));


      holli, /regexed monk/