#!/usr/bin/env perl use strict; use warnings; my $data = '43:1:1; 43:1:2; 43:1:3; 43:1:4; 43:1:5; 43:1:6; 27:3:7; 27:3:8; 27:3:9; 65:1:4; 65:1:18'; $data .= '; 43:1:8; 65:1:9; 65:1:3; 1:1:2; 1:1:1'; my %seqs_for; my @key_order; for (split /; /, $data) { my ($key, $seq) = /^(\d+:\d+):(\d+)$/; push @key_order, $key unless exists $seqs_for{$key}; push @{$seqs_for{$key}}, $seq; } my @output; for my $key (@key_order) { my ($out, $last_seq, $end_range) = ('', -2, ''); my @sorted_seqs = sort { $a <=> $b } @{$seqs_for{$key}}; for my $i (0 .. $#sorted_seqs) { my $seq = $sorted_seqs[$i]; if (length $out) { if ($seq == $last_seq + 1) { $end_range = $seq; } else { $out .= "-$end_range" if $end_range; push @output, $out; $out = "$key:$seq"; $end_range = ''; } } else { $out = "$key:$seq"; } $last_seq = $seq; if ($i == $#sorted_seqs) { $out .= "-$end_range" if $end_range; push @output, $out; } } } print join('; ', @output), "\n";