Home: Perl Programming Help: Beginner:
Not counting strings correctly


May 10, 2017, 9:54 AM

Views: 1339
Not counting strings correctly

Hello Perl Gurus,

Can somebody offer some advise as to why this isn't counting correctly within my loop. I am searching through a file looking for specific accounts (AE202B01/AE202B02/AE202B03).

My desired output would be to count all occurences of them.

AE202B01 5
AE202B02 3
AE202B03 2

my output is coming out:

AE202B01 1
AE202B01 1
AE202B01 1
AE202B01 1
AE202B01 1
AE202B02 1
AE202B02 1
AE202B02 1
AE202B03 1
AE202B03 1

use strict;
use warnings;
use MIME::Lite;
use File::stat;
use Time::localtime;
use List::Util qw(sum);

my $Accounts;
my $count;
my $counts;
my $OUT;
my $char;
my @Accounts = ('AE202B01','AE202B02','AE202B03');

my $emd = `date --date '-30 min' +'%H'`;
chop ($emd);

$emd = "/tmp/pathtomyfiles/$emd.txt";

my %count;
my $outfile = "/tmp/script/AESTUFF/AE202b.txt";

open (my $fh1, "-|" , "$emd") || die "Failed: $!\n" ; open ($OUT, "> $outfile") || die "Cannot open $outfile"; # temp file to which to write the formated output, if there is a match

while (my $line = <$fh1>) {
chomp ($line);
$line =~ s/ /\n/;
# $line =~ s/.*UserId1://;
# $line =~ s/}.*//;
# $line =~ s/,pairId:.*//;
if ( $line =~ /UserId1:(\w+),pairId.*/ ) {
$Accounts = $1;

foreach (@Accounts) {

if ($Accounts =~ /$_/ ){

foreach my $str (split /\s+/, $Accounts) {

foreach my $str (sort keys %count) {
printf "%-31s %s\n", $str, $count{$str};

close ($OUT);

Appreciate the assistance --

Veteran / Moderator

May 11, 2017, 3:58 AM

Views: 1327
Re: [new2perl2016] Not counting strings correctly

If you took the time to indent your code correctly, not only you make the life of those trying to help you easier (and that would be quite polite), but you would also probably figure out easily by yourself what's wrong with your code.

So, please indent your code correctly, and post it if you still don't know what's wrong.