Poisson
Poisson

Reputation: 1623

Search an element in a hash table

I have created a hash table from a text file like this:

use strict;
use warnings;

my %h;

open my $fh, '<', 'tst' or die "failed open 'tst' $!";
while ( <$fh> ) {
  push @{$h{keys}}, (split /\t/)[0];
}
close $fh;

use Data::Dumper;
print Dumper \%h;

Now I want to look for a field in another text file in the hash table. if it exists the current line is written in a result file:

use strict;
use warnings;

my %h;

open my $fh, '<', 'tst' or die "failed open 'tst' $!";
while ( <$fh> ) {
  push @{$h{keys}}, (split /\t/)[0];
}
close $fh;


use Data::Dumper;
print Dumper \%h;

open (my $fh1,"<", "exp") or die "Can't open the file: ";

while (my $line =<$fh1>){

chomp ($line);



my ($var)=split(">", $line);

if exists $h{$var};
print ($line);

}

I got these errors:

syntax error at codeperl.pl line 26, near "if exists" 
Global symbol "$line" requires explicit package name at codeperl.pl line 27. 
syntax error at codeperl.pl line 29, near "}" 
Execution of codeperl.pl aborted due to compilation errors.

Any idea please?

Upvotes: 1

Views: 170

Answers (2)

akawhy
akawhy

Reputation: 1608

just try your code like this

First, build your hash

while(<$file1>){
    # get your key from current line
    $key = (split)[0];

    # set the key into the hash
    $hash{$key} = 1;
}

Second, judge

while(<$file2>){
     # get the field you want you judge
     $value = (split)[0];

     # to see if $value exists
     if( exists $hash{$value} ){
         print "got $value";
     }
}

Upvotes: 0

amon
amon

Reputation: 57640

What is there to say? The statement if exists $h{$var}; is a syntax error. You may want:

print $line, "\n" if exists $h{$var};

or

if (exists $h{$var}) {
  print $line, "\n";
}

The other errors will go away once you fixed that. If you get multiple errors, always look at the first error (with respect to the line numbers). Later errors are often a result of a previous one. In this case, the syntax error messed up the parsing.


Edit

your main problem isn't the syntax error, it is how you populate your hash. The

push @{$h{keys}}, (split /\t/)[0];

pushes first field on the line onto the arrayref that is in the keys entry. To me, it seems that you actually want to use this field as the key:

my ($key) = split /\t/;
$h{$key} = undef;   # any value will do.

After that, your Dumper \%h will produce something like

$VAR1 = {
  '@ ries bibliothèques électroniques à travers' => undef,
  'a a pour les ressortissants des'              => undef,
  'a a priori aucune hiérarchie des'             => undef,
};

and your lookup via exists should work.

Upvotes: 3

Related Questions