use List::MoreUtils qw{uniq} while (){ chomp; convert each line to an array of numbers splitting by "-" sort the resulting list of numbers and apply uniq to this list: my @list_of_unique_items = uniq @list; join or print again each element followed by a "-" chomp again if needed to delete the last "-" undef the array process the next line