Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Yet Another List to Range function.

by shotgunefx (Parson)
on Jun 19, 2002 at 03:33 UTC ( #175558=snippet: print w/replies, xml ) Need Help??
Description: Yet Another List to Range function. The two I'm aware of on the site didn't work for me. one doesn't handle numbers that begin with zero and the other seems to have a bug. Takes an array and in list context returns an array. In scalar it returns a string. Ranges are separated by \s-\s so that you can easily split them without worrying about confusing them with negative numbers.
Handles numbers that begin with 0 as well. If not ints, makes a weak effort to handle fractions intervals. If your numbers are fractional and normalized, it should work ie ( 0.5 0.6 0.7)
(0.1 0.2 0.3) # Will work (0.1 00.20 0.3) # Won't work
Changed description
#!/usr/bin/perl -w
use strict;

sub list2ranges {
    my @list = sort {$a<=>$b} @_;
    my $current = $list[0];
    my @ranges = ($current) ;
    for (my $i=1;$i <= @list; $i++){
        if ($list[$i] && $list[$i] - $current == 1 || $list[$i] && $li
+st[$i] - $current < 1  && substr($list[$i],0,-1) eq substr($current,0
+,-1) ){
            $current = $list[$i];
              $ranges[-1] .= " - $current" if $ranges[-1] != $current;
              $list[$i] && push @ranges, $current = "$list[$i]" ;

    return wantarray ? @ranges : join(", ",@ranges);

# Examples
my @test = (qw( 01 2 3), 5, (7..9), (11..12), (17..19), 20, 30, qw(30.
+1 30.2 30.33 30.34 30.35));
my @ranged = list2ranges(@test);

print join(", ",@test)," \n";
print join(", ",@ranged)," \n";
print scalar(list2ranges(@test)),"\n";
Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://175558]
[marioroy]: Well, that's why there must be angels around, invisible or not.
[marioroy]: Lady_Aleena yes, ladder.
[marioroy]: Corion, no not intentionally. not at all.
[Lady_Aleena]: /ne tries to decide whther or not to take a hammer to hubby's alarm clock.
[Lady_Aleena]: He never hears it.
[marioroy]: Back in HighSchool, I came late to Gym class. There was a fellow who was picked last, no team wanted him for racketball. So it was us two against everybody. I looked at him in the eye and said to let your body loose and let the powers to be help us win.
[marioroy]: We made it all the way to the end. The expience was magical. I not good at sports. Someone or thing was there.
erix considers extracting a catalog ...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (12)
As of 2017-05-29 08:41 GMT
Find Nodes?
    Voting Booth?