F
fmassion
I have 2 lists:
List of words:
cat
dog
List of phrases:
This is a cat
This is another cat
This is a dog
This is a cat and not a dog
I wand have a hash with all phrases (=values) matching the word "cat" (key) or "dog" (other key)
In my code I only get the last value of each search. Obvisouly I am doing something wrong here. Any suggestions?
Here my code:
#!/usr/bin/perl -w
# Open words file
open(WORDLIST,$ARGV[0]) || die("Cannot open $ARGV[0]!\n");
@words = <WORDLIST>;
# Close words file
close(WORDLIST);
# Open phrases file
open(PHRASELIST,$ARGV[1]) || die("Cannot open $ARGV[1])!\n");
@phrase = <PHRASELIST>;
# Close phrases file
close(PHRASELIST);
# Create empty hash for results
%phrasefound = ();
foreach $word (@words) {
for($phrasecount=0 ; $phrasecount <= $#phrase ; $phrasecount++) { # Counts from 0 to last array entry
$phrase = $phrase[$phrasecount];
chomp $word;
chomp $phrase;
if ($phrase =~ m/$word/i) {
# push into hash
$phrasefound{$word} = $phrase;
print $word."-->".$phrasefound{$word}."\n"; #this is to check if it works. I get here all values
}}}
# output hash
print "Hash result:\n----------\n";
foreach $word (keys %phrasefound) {
print "$word --> $phrasefound{$word}\n"; #I get only the last match
}
List of words:
cat
dog
List of phrases:
This is a cat
This is another cat
This is a dog
This is a cat and not a dog
I wand have a hash with all phrases (=values) matching the word "cat" (key) or "dog" (other key)
In my code I only get the last value of each search. Obvisouly I am doing something wrong here. Any suggestions?
Here my code:
#!/usr/bin/perl -w
# Open words file
open(WORDLIST,$ARGV[0]) || die("Cannot open $ARGV[0]!\n");
@words = <WORDLIST>;
# Close words file
close(WORDLIST);
# Open phrases file
open(PHRASELIST,$ARGV[1]) || die("Cannot open $ARGV[1])!\n");
@phrase = <PHRASELIST>;
# Close phrases file
close(PHRASELIST);
# Create empty hash for results
%phrasefound = ();
foreach $word (@words) {
for($phrasecount=0 ; $phrasecount <= $#phrase ; $phrasecount++) { # Counts from 0 to last array entry
$phrase = $phrase[$phrasecount];
chomp $word;
chomp $phrase;
if ($phrase =~ m/$word/i) {
# push into hash
$phrasefound{$word} = $phrase;
print $word."-->".$phrasefound{$word}."\n"; #this is to check if it works. I get here all values
}}}
# output hash
print "Hash result:\n----------\n";
foreach $word (keys %phrasefound) {
print "$word --> $phrasefound{$word}\n"; #I get only the last match
}