Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

retain the query order-hash not helpful 1

Status
Not open for further replies.

3inen

Technical User
May 26, 2005
51
US
Hi!
i have a query list in file2 and want to print the data from file1 when there is a match in column 1 of file1. as you can see with the code i have, the query order in the file1 is not retainded b'se i am using hash. can any body help in retaining the query order.

thanks in advance


#!/usr/bin/perl -w
open(FH1, "file1.txt");
open(FH2, "file2.txt ");

my @arr1 = map {chomp; [split]} <FH1>;
my %h1 = map {chomp; $_ => undef} <FH2>;

close(FH1);
close(FH2);

my @arr2 = grep {exists($h1{$_->[0]})} @arr1;
print join("\t", @$_), "\n" for @arr2;


expected output would be

A1 30
B9 30.08
B1 29
C9 31.08


and not

A1 30
B1 29
B9 30.08
C9 31.08
an so on



file1.txt
A1
B9
B1
C9


file2.txt

A1 30
A2 30
A3 28
B1 29
B2 28
B9 30.08
B10 29
C8 23
C9 31.08

 
How about something like this:
Code:
open FILE1, "< file1.txt" or die;
open FILE2, "< file2.txt" or die;

my @a1 = map {chomp; $_} <FILE1>;
my %h1 = map {split} <FILE2>;

foreach (@a1) {
    if ($h1{$_}) {
        print "$_\t$h1{$_}\n";
    }
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top