You didn't mention what you want when your input includes a sequence like this:
..., 0.3, 0.58, 0.2, ...
Supposing the "0.58" was the 20th element in the list, should that produce a "segment" like this?
20
or like this?
20 20
Anyway, the fact that your solution works fine (once you add some very simple post-processing on @segments) seems good enough to me. But in case you want to generalize it to different conditions and without having to rewrite it every time (and rewrite the post-processing too), here's one approach for a general-purpose subroutine, which would be easy to pop into a module, if you like:
#!/usr/bin/perl use strict; use warnings; my @probs; { local $/; @probs = split " ", <DATA>; } my $segs = get_ranges( sub { return ( $_[0] > 0.5 ) }, \@probs ); print "$_\n" for ( @$segs ); sub get_ranges { my ( $cmp, $list ) = @_; my @ranges = (); my @current_range = (); my $endpoint = 0; for ( 0 .. $#$list ) { if ( $cmp->( $$list[$_] )) { $current_range[$endpoint] = $_; $endpoint = 1; } elsif ( @current_range ) { push @ranges, "@current_range"; @current_range = (); $endpoint = 0; } } return \@ranges; } __DATA__ 0 0.1 0.53 0.51 0.59 0.67 0.2 0.04 0.05 0.56 0.89 0.75 0.3 0.58 0.25
The idea is that from one application to the next, you might need to change your conditions for determining what sort of range you want to identify, so you simply supply a suitable subroutine along with the input list.

(Updated to simplify the anon.sub that is passed to get_ranges; $cmp->($item) just needs to return true when $item is in the targeted range.)


In reply to Re: printing array positions that match a condition by graff
in thread printing array positions that match a condition by coldy

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.