G'day Polyglot,
I see you already have a number of solutions.
Here's another with no complex regexes nor any CPAN requirements.
#!/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";
Note that I added a few more data elements mainly for testing purposes:
$data .= '; 43:1:8; 65:1:9; 65:1:3; 1:1:2; 1:1:1';
Output:
43:1:1-6; 43:1:8; 27:3:7-9; 65:1:3-4; 65:1:9; 65:1:18; 1:1:1-2
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.