3

I've got an array in perl which contains sorted non-contiguous values. For example: 1 2 3 5 7 11 13 15.

I want to remove all values that are outside lower and upper, keeping lower and upper in the returned selection. My method of doing that looks like this (could probably be improved by using slice):

my @culledArray;
for ( my $i = 0; $i < scalar(@array); $i++ ) { 
    if ( ( $array[$i] <= $_[1] ) and ( $array[$i] >= $_[0] ) ) { 
       push(@culledArray, $array[$i]);
    }
}

where the lower and upper are contained in $_[0] and $_[1], respectively. Is there a perl builtin that does this?

3 Answers 3

4

Don't know anything built-in that would do that (that is quite a specific requirement), but you can save yourself some typing by using grep:

my @culledArray = grep {( $_ <= $_[1] ) and ( $_ >= $_[0] )} @array;

If the list is long and you don't want to copy it, finding the start and end indices and using a slice might be interesting.

1

This is messy, but my unit tests pass, so it seems to work. Take the lower and upper indexes, based on the fact that @array is a sorted list and $_[0] >= $_[1], then create the @culledArray from @array[$lower..$upper]:

my @culledArray;
my $index = 0;
++$index until $array[$index] >= $_[0];
my $lowerIndex = $index;
while (($array[$index] <= $_[1]) and ($index < $#array)) { ++$index; }
my $upperIndex = $index;

@culledArray = @array[$lowerIndex .. $upperIndex];
return \@culledArray;

I'd love to know the efficiency of this vs the answer Mat gave. I'm almost sure that I don't necessarily traverse the entire @array (because I traverse from index of 0 until I find the $upperIndex. I'm not sure how the grep method in the linked answer works, or how perl implements the slicing of @array to @culledArray in the above code, though.

1
  • If you're looking for efficiency, with a large list, a binary search (since the array is sorted) would be much more efficient than what you propose. grep goes through the whole array, so it would be less efficient than your method if there are many elements over the upper bound (and the array is large).
    – Mat
    May 28, 2012 at 6:23
0

It looks like you may be using percentiles or quantiles? If so then Statistics::Descriptive may help.

The percentile method returns the value and index at that percentile, so you can use code as below

use strict;
use warnings;

use Statistics::Descriptive;

my @data = qw/ 1 2 3 5 7 11 13 15 /;

my $stat = Statistics::Descriptive::Full->new;
$stat->add_data(@data);
my ($d25, $i25) = $stat->percentile(25);
my ($d75, $i75) = $stat->percentile(75);

my @subset = ($stat->get_data)[$i25 .. $i75];

print "@subset\n";

output

2 3 5 7 11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.