Here is an OO approach - makes the code a little more readable
#!/usr/bin/perl -w use strict; use Data::Dumper 'Dumper'; { package Range; sub new{ my $class = shift; return bless {map { $_=> shift} qw[NAME START FIN]}, $class; } sub contains{ my ($self, $other) = @_; return $self->{START} <= $other->{START} && $self->{FIN} >= $other->{FIN} ; } sub add_subrange{ my ($self, $other) = @_; push @{$self->{SUBRANGES}}, $other; } 1 } #--- Main code --- my @ranges = ( new Range(qw[A 11 22]), new Range(qw[B 22 45]), new Range(qw[C 22 33]), new Range(qw[D 25 28]), new Range(qw[E 47 49]), ); for my $r1 (@ranges){ for my $r2(@ranges){ next if $r1 == $r2; $r1->add_subrange($r2) if $r1->contains($r2); } print Dumper \$r1; }
Result:
$VAR1 = \bless( { 'NAME' => 'A', 'START' => 11, 'FIN' => 22 }, 'Range' ); $VAR1 = \bless( { 'NAME' => 'B', 'START' => 22, 'SUBRANGES' => [ bless( { 'NAME' => 'C', 'START' => 22, 'FIN' => 33 }, 'Range' ), bless( { 'NAME' => 'D', 'START' => 25, 'FIN' => 28 }, 'Range' ) ], 'FIN' => 45 }, 'Range' ); $VAR1 = \bless( { 'NAME' => 'C', 'START' => 22, 'SUBRANGES' => [ bless( { 'NAME' => 'D', 'START' => 25, 'FIN' => 28 }, 'Range' ) ], 'FIN' => 33 }, 'Range' ); $VAR1 = \bless( { 'NAME' => 'D', 'START' => 25, 'FIN' => 28 }, 'Range' ); $VAR1 = \bless( { 'NAME' => 'E', 'START' => 47, 'FIN' => 49 }, 'Range' );

     "As you get older three things happen. The first is your memory goes, and I can't remember the other two... " - Sir Norman Wisdom


In reply to Re: sorting and grouping by by NetWallah
in thread sorting and grouping by by jperlq

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.