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!


In reply to Perl beginner's issue with hash by Maire

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.