use strict; use warnings; my $string = 'Return code is'; my $filename = 'trace.Discovery'; my %errors =(); my $total = 0; if (open(my $fh, '<:encoding(UTF-8)', $filename)) { while (my $row = <$fh>) { chomp $row; if ($row =~ /\Q$string\E/) { my $digit = (split /\:/, $row)[-1]; $errors{$digit}++; } } } else { print "Could not open file '$filename'\n"; warn "This is the error --> $!"; } # First attempt to print keys foreach ( sort keys %errors ) { print "$_ - $errors{$_}\n"; $total = $total + $errors{$_}; } print "Total errors --> $total\n"; ### Another attempt to print the keys. while( my( $key, $value ) = each %errors ){ print "$key: $value\n"; }