#!/usr/bin/env perl use warnings; use strict; # Usage: perl ./most-substrings.pl "R" ./example.txt my $substr = shift @ARGV; my %counts; while (my $line = <>) { chomp $line; # Get a count of matching substrings: my @matches = $line =~ m/$substr/g; my $count = scalar @matches; $counts{$line} = $count } # Find the highest count of substring: my $max = 0; foreach my $count (values %counts) { $max = $count if $count > $max; } # For every line, check if its count is the highest we hit: foreach my $line (keys %counts) { print "$line\n" if $counts{$line} == $max; }