Hi All, I'm a Perl beginner trying to do something very basic and encountering an issue. I want to find how many times each item in an array appears in a separate .txt document - when an item doesn't appear an error message should be printed. I have cobbled together the code below from various sources and it seemed to work at first glance, but the script only counts one instance of each item.
@ids = ("a", "b", "c", "d", "e", "f", "g",);
my %counts;
foreach my $id (@ids)
{
open(FILE, "list.txt" ) || die "couldn't open 2\n";
$/ = undef;
while (<FILE>) {
if (/$id/g) {
$counts{$id}++;
}
else {
print "$id not found\n";
}
}
close FILE;
}
use Data::Dumper;
print Dumper \%counts;
Sorry I can't work out how to include the contents of list.txt into the above code - I've included it below instead
a
b
b
c
c
d
d
d
f
f
f
This script returns:
e not found
g not found
$VAR1 = {
'f' => 1,
'c' => 1,
'b' => 1,
'd' => 1,
'a' => 1
};
When I'm expecting:
e not found
g not found
$VAR1 = {
'f' => 3,
'c' => 2,
'b' => 2,
'd' => 3,
'a' => 1
};
My uneducated guess is that it is the way I am reading in list.txt that is 'wiping' the hash, but unfortuantely I have no idea how to fix it. Any tips would be very much appreciated. Thank you in advance!