Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Perl beginner's issue with hash

by BillKSmith (Monsignor)
on Apr 24, 2020 at 03:04 UTC ( [id://11116000]=note: print w/replies, xml ) Need Help??


in reply to Perl beginner's issue with hash

Read the entire file into an array rather than opening and reading it inside the loop. Use grep in scalar context to do the counting.
use strict; use warnings; use Data::Dumper; my $file = \"a\nb\nb\nc\nc\nd\nd\nd\nf\nf\nf"; # In memory 'file' my @ids = qw( a b c d e f g ); open my $FILE, '<', $file or die "cannot open input file"; my @lines = <$FILE>; # Read entire file into an array close $FILE; my %counts; ID: foreach my $id (@ids) { my $count = grep { /$id/ } @lines; if ($count) { $counts{$id} = $count; next ID; } warn "$id not found\n"; } print Dumper \%counts;
OUTPUT: e not found g not found $VAR1 = { 'd' => 3, 'a' => 1, 'c' => 2, 'f' => 3, 'b' => 2 };
Bill

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11116000]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2024-04-24 12:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found