Baptiste Baptiste - 4 months ago 14
Perl Question

Perl compare array content to hash values

I'm trying to check the existence of words from a file in a hash, and if so to display the corresponding hash key and value.

So far, I've been able to do it with an array

@motcherches
which values are given in the script.

I can't find a way to give as values to this array words from a external file (here
FILEDEUX
).
Could you point me in the right direction?

(Please don't hesitate to correct my way of explaining my problem.)

#!/usr/bin/perl
use v5.10;
use strict;
use warnings;
my $hashtable = $ARGV[0];
my $textecompare = $ARGV[1];
open FILE,"<$hashtable" or die "Could not open $hashtable: $!\n";
open FILEDEUX,"<$textecompare" or die "Could not open $textecompare: $!\n";


while ( my $line = <FILE>)
{
chomp($line);
my %elements = split(" ",$line);

my @motcherches = qw/blop blup blip blap/;
foreach my $motcherches (@motcherches) {

while ((my $key, my $value) = each (%elements)) {
# Check if element is in hash :
say "$key , $value" if (exists $elements{$motcherches}) ;
}
}
}

close FILE;
close FILEDEUX;


EDIT: Example inputs

FILE
(transformed into
%elements
hash)

Zieler player
Chilwell player
Ulloa player
Mahrez player
Ranieri coach


============================================================================

FILEDEUX
(transformed into
motcherches
array)

One save is quickly followed by another, and this time Zieler had to be a little sharper to keep it out.
Izaguirre gives Mahrez a taste of his own medicine by beating him all ends up down the left flank, although the Leicester winger gave up far too easily.
Claudio Ranieri will be happy with what he has seen from his side so far.

=============================================================================

Expected output:

Zieler player
Mahrez player
Ranieri coach

Answer
use strict;
use warnings;
use feature qw/ say /;  

# Read in your paragraph of text here:
open my $text, '<', 'in.txt' or die $!; 

my %data;
while(<$text>){
    chomp;
    $data{$_}++ for split; # by default split splits on ' '
}

my %players;
while(<DATA>){
    chomp;
    my @field = split;
    say if $data{$field[0]};
}


__DATA__
Zieler player
Chilwell player
Ulloa player
Mahrez player
Ranieri coach