use Modern::Perl; my %count; my $railcarcnt = qr(Boxcar|Reefer|Flatcar|Tankcar|Gondola|Hopper); while () { $count{$1}++ if /($railcarcnt)/i; } foreach my $word ( sort keys %count ) { say "There are $count{$word} $word Car(s)"; } __DATA__ B&LE:65065:Hopper:Home B&LE:65700:Hopper:Home VM:51142:Hopper:Home OS:1400:Hopper:Home HT&SF:1234:Flatcar:Away NMBS:999:Reefer:Gone