For example, I have an array = [1,2,3,4,5,a,#,4] how can I check if an array has an element that's not integer? If an array has an element that's not integer than I am planning to fail the script which is die function.
CodePudding user response:
Type::Tiny provides a quick method (all
) to check if all elements in a list match a specific type consrtaint.
use strict; use warnings; use feature qw( say );
use Types::Common qw( Int PositiveInt );
my @array = ( 1, 2, 3, "foo" );
if ( not Int->all( @array ) ) {
say "They're not all integers";
}
if ( PositiveInt->all( @array ) ) {
say "They're all positive integers";
}
# Another way to think about it:
my $NonInteger = ~Int;
if ( $NonInteger->any( @array ) ) {
say "There's at least one non-integer";
}
CodePudding user response:
If quick&dirty is good enough:
my @a = (1,2,3,-4,0,5,4," -32 ");
die if grep { !defined or !/^\s*-?\d \s*$/ } @a;
This however doesn't handle for example valid integers (in Perl) such as "1_200_499"
or "0e0"
well.