Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Regexp substitution on variable-length ranges with embedded code?

by kcott (Archbishop)
on May 27, 2021 at 11:18 UTC ( [id://11133119]=note: print w/replies, xml ) Need Help??


in reply to Regexp substitution on variable-length ranges with embedded code?

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11133119]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2024-04-18 20:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found