Supposing the "0.58" was the 20th element in the list, should that produce a "segment" like this?..., 0.3, 0.58, 0.2, ...
or like this?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:20 20
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.#!/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
(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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |