Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

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

— Ken


In reply to Re: Regexp substitution on variable-length ranges with embedded code? by kcott
in thread Regexp substitution on variable-length ranges with embedded code? by Polyglot

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • 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 or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (2)
As of 2022-05-26 02:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (92 votes). Check out past polls.

    Notices?