#!/usr/bin/env perl use Data::Dumper; # I like to dump stuff use strict; # "strict" and "warnings" are a best practice use warnings; my %encountered; # We're going to "stuff" the numbers encountered here while () { chomp; while (m{(\d+)}g) { # Find numbers in the string one set (2019) at a time push @{$encountered{$1}},$_; # Note 1 will occur twice in the line "1 this year is 2019 1" }; }; # Dump them with a label (and file and line number) so we can verify warn Data::Dumper->Dump([\%encountered],[qw(*encountered)]),' '; # Print them longest first local $"=qq{', '}; #" # To make them more readable for my $number (sort {$b <=> $a} keys %encountered) { # Sort largest number first print "$number: '@{$encountered{$number}}'\n"; }; __END__ Hello, i'm 18 1 this year is 2019 1 1 2 3 - 4