On 2/25/2014 7:07 PM, Jim Gibson wrote:

On Feb 25, 2014, at 2:30 PM, Bill McCormick wrote:

What would be the perl'ish way using map or some other sugar to check if a list 
of values meet some criteria? Instead of doing something like

my @issues = qq(123,456,a45);
my $max = 999;

for (@issues) {
  die if $_ < 0 or $_ > $max;
}

I want to check if each list item is numeric and > 0 but less than $max.

Cheers!

grep is the Perl function for testing a list of values against some criteria.

perldoc -f grep

'grep BLOCK LIST' will return all of the items in LIST that result in a true 
value when BLOCK is evaluated. In scalar context, grep returns the number of 
items that evaluated to true, so you can either save all of the true-ish items 
or just get a count.

For example (untested):

my @fail = grep { $_ =~ /\D/ || $_ <= 0 || $_ >= $max } @issues;

Now @fail contains any member of @issues that fails any of the three tests:
   1) contains a non-digit,
   2) is less than or equal to zero,
   3) greater than or equal to $max

If @fail is empty, everybody passed (that is, evaluated to false!)


$_ =~ /\D/ matches for negative numbers. Also, once the list is built, the reason why it is in the list is gone. I still see that a for loop is the best approach.


---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com



--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to