rmocster has asked for the wisdom of the Perl Monks concerning the following question:

Is there a library to convert an array with padded numbers to a padded range and separated ranges with comma. For example, I like to convert (0001,0002,0003,011,012,013,015) to "0001-0003,011-013,015". Thanks. I found something similar http://www.perlmonks.org/?node_id=87538 but it doesn't do padded numbers.
  • Comment on Convert an array of numbers into a range

Replies are listed 'Best First'.
Re: Convert an array of numbers into a range
by AnomalousMonk (Archbishop) on Jul 22, 2016 at 00:03 UTC

    <pedantry>

    ... an array with padded numbers ... (0001,0002,0003,011,012,013,015) ...

    Just BTW, and perhaps to avoid a subsequent misunderstanding, that's an array of octal numbers.

    c:\@Work\Perl\monks>perl -wMstrict -le "use Data::Dump qw(dd); ;; my @ra = (0001,0002,0003,011,012,013,015); dd \@ra; " [1, 2, 3, 9, 10, 11, 13]
    See in particular the "true" (i.e., decimal) value of 015.

    Might you be thinking of something like  qw(0001 0002 0003 011 012 013 015) instead?

    c:\@Work\Perl\monks>perl -wMstrict -le "use Data::Dump qw(dd); ;; my @ra = qw(0001 0002 0003 011 012 013 015); dd \@ra; " ["0001", "0002", "0003", "011", "012", "013", "015"]

    </pedantry>


    Give a man a fish:  <%-{-{-{-<

      I am thinking @ra = qw(0001 0002 0003 011 012 013 015); or added couple numbers :) @ra = qw(0001 0002 0003 011 012 013 015 16 17 18 20); How is regex be structured? Thanks a lot.

        For older perls without the /r

        #!/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}))+/-$2/g; print;
        #!/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); print join(',', @ra) =~ s/\b(\d+)(?{$1})\K(?:,(\d+)\b(??{++$^R!=$2}))+ +/-$2/gr;
Re: Convert an array of numbers into a range
by Discipulus (Canon) on Jul 22, 2016 at 06:55 UTC
    you can also find Perl Module for dealing with number ranges interesting to read

    L*

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Re: Convert an array of numbers into a range
by Anonymous Monk on Jul 21, 2016 at 23:36 UTC
    #!/usr/bin/perl -l # http://perlmonks.org/?node_id=1168288 use strict; use warnings; my $list = '0001,0002,0003,011,012,013,015'; print $list =~ s/\b(\d+)(?{$1})\K(?:,(\d+)\b(??{++$^R!=$2}))+/-$2/gr;
      I get this error: Bareword found where operator expected on the print line. Execution aborted due to compilation errors.

        Too old a perl ?