use strict; use warnings; my %strings; foreach my $line () { $line =~ m/(\d+)/; my $class = $1; # Save the line in an array for this class of line # Keep references to the arrays in a hash keyed by # the class. Use push() to add each line to the array. push(@{$strings{$class}}, $line); } # Now iterate over the classes and print all the lines # for each class. foreach my $class (sort { $a <=> $b } keys %strings) { print "strings for class $class:\n"; foreach my $string (@{$strings{$class}}) { print "\t$string"; } } __DATA__ BLABLABLA 2 BLABLA BLABLABLA 2 BLABLA BLABLABLA 2 BLABLA BLABLALBA 3 BLABLA BLABLABLA 3 BLABLA