If you know the number of messages available ahead of time, you could pass that along with the range string to this function. It will return undef if the string is invalid, otherwise it will return a reference to an array containing each message number in question based on a given range.
sub range_populate {
my ($max, $range) = @_;
my @range = ();
if ($range eq 'a') { return \@{[0..$max]}; }
elsif ($range !~ /[-,]/) { push @range, $range; }
else {
my @mini = split /,/, $range;
for (@mini) {
return undef if /-.*?-/; # 1 dash per subsection, e.g., "2
+-6-9, 24" is invalid
if ( !/-/ ) { push @range, $_; }
else {
return undef unless /(\d+)-(\d+)/;
return undef unless $1 < $2;
push @range, ($1..$2);
}
}
}
return undef if $#range == -1;
for (@range) { return undef unless ($_ >= 0 && $_ <= $max); }
return \@range;
}
# example
my $num_messages = 10;
my $sample_range = '3-6,9';
my $rng_ref = &range_populate ($num_messages, $sample_range); # return
+s reference to array (3, 4, 5, 6, 9)