in reply to Re^3: Convert an array of numbers into a range
in thread Convert an array of numbers into a range

this sort of works.

result: 0001-0003,011-013,015-18,20

should be: 0001-0003,011-013,015,16-18,20

  • Comment on Re^4: Convert an array of numbers into a range

Replies are listed 'Best First'.
Re^5: Convert an array of numbers into a range
by Anonymous Monk on Jul 22, 2016 at 01:01 UTC

    Changing the rules in the middle of the game?

    Next time give exact desired output when you pose a problem.

      Sorry, not meant to mislead.
Re^5: Convert an array of numbers into a range
by Anonymous Monk on Jul 22, 2016 at 01:07 UTC
    #!/usr/bin/perl -l # http://perlmonks.org/?node_id=1168288 use strict; use warnings; my @ra = qw(0001 0002 0003 011 012 013 015 16 17 18 20); $_ = join ',', @ra; s/\b(\d+)(?{$1})\K(?:,(\d+)\b(??{++$^R!=$2||length$1!=length$2}))+/-$2 +/g; print;
      WOW, that is perfect. Big Thanks. Can you give a brief explanation of the syntax if you don't mind? Again thanks.
        #!/usr/bin/perl -l # http://perlmonks.org/?node_id=1168288 use strict; use warnings; my @ra = qw(0001 0002 0003 011 012 013 015 16 17 18 20); $_ = join ',', @ra; s/\b # find a number boundary (\d+) # and a number $1 (?{$1}) # save the number in $^R \K # then leave the above in the string (?: # non-capture grouping , # comma - also forces $1 to be a complete number (\d+) # a complete number (because of , and \b) \b # forces comlete number (??{ # extended pattern ++$^R != $2 # false if correct number || length$1 != length$2 # false if same length }) # false (and therefor matches) if both false, other +wise fails # if true returns 1 which can't match because of th +e \b )+ # repeat at least once /-$2/gx; # replace second or more with last matching number print;

      I got this error.

      Complex regular subexpression recursion limit (32766) exceeded

      s/\b(\d+)(?{$1})\K(?:,(\d+)\b(??{++$^R!=$2||length$1!=length$2}))+/-$2 +/g;