Maire has asked for the wisdom of the Perl Monks concerning the following question:
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.
Sorry I can't work out how to include the contents of list.txt into the above code - I've included it below instead@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;
a b b c c d d d f f f
This script returns:
When I'm expecting:e not found g not found $VAR1 = { 'f' => 1, 'c' => 1, 'b' => 1, 'd' => 1, 'a' => 1 };
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!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Perl beginner's issue with hash
by choroba (Cardinal) on Apr 23, 2020 at 15:48 UTC | |
by Maire (Scribe) on Apr 23, 2020 at 15:50 UTC | |
by AnomalousMonk (Archbishop) on Apr 23, 2020 at 18:50 UTC | |
|
Re: Perl beginner's issue with hash
by GrandFather (Saint) on Apr 23, 2020 at 20:26 UTC | |
|
Re: Perl beginner's issue with hash
by haukex (Archbishop) on Apr 23, 2020 at 19:47 UTC | |
|
Re: Perl beginner's issue with hash
by BillKSmith (Monsignor) on Apr 24, 2020 at 03:04 UTC |