use strict; use warnings; # Convert ( 1,2,3,7,9,10,11,12) to '1-3,7,9-12'. # # Handles duplicate numbers (by ignoring them), reals, out # of order elements*, and changes in sign within the array. # # * Well, I guess I should say that it assumes you want # 'normal' order and not necessarily the order given. # sub num2range( @ ) { my ( @end_points , @ranges ); @_ = sort { $a <=> $b } @_; # Construct the first interval. $end_points[ 0 ] = $end_points[ 1 ] = shift; # We're done! ... Unless there's more than one element in # the array. :) @_ or return wantarray ? ( $end_points[ 0 ] ) : $end_points[ 0 ]; # Scan through the rest of the array, building on the # current endpoint until we get to a jump. Whereupon we # push the current endpoint into the list of ranges, and # initialize a new interval with the current element. for ( @_ ) { if ( $_ - $end_points[ 1 ] == 1 ) { $end_points[ 1 ]++; } else { unless ( $_ == $end_points[ 1 ] ) { push @ranges , ( $end_points[ 0 ] == $end_points[ 1 ] ) ? "$end_points[ 0 ]" : "$end_points[ 0 ]-$end_points[ 1 ]"; } @end_points = ( $_ , $_ ); } } # The last element is special since it has no antecedant # and, hence, will never be processed by the push above. push @ranges , ( $end_points[ 0 ] == $end_points[ 1 ] ) ? "$end_points[ 0 ]" : "$end_points[ 0 ]-$end_points[ 1 ]"; return wantarray ? @ranges : join( ',' , @ranges ); } # For example: # print scalar num2range( 1,2,2.5,3.5,4.5,7,6,-5,-6,-7,7,8,9,10,0,12,42-24 ); # Gives: # -7--5,0-2,2.5-4.5,4.6,6-10,12,18