-3

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.

brian d foy
  • 129,424
  • 31
  • 207
  • 592
x2ffer12
  • 111
  • 5
  • 1
    Does this answer your question? [How can I filter an array without using a loop in Perl?](https://stackoverflow.com/questions/3960028/how-can-i-filter-an-array-without-using-a-loop-in-perl) Couple that with the integer case from [How can I tell if a variable was a numeric value in Perl?](https://stackoverflow.com/questions/12647/how-do-i-tell-if-a-variable-has-a-numeric-value-in-perl) – tripleee Jan 23 '23 at 09:11

2 Answers2

2

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";
}
tobyink
  • 13,478
  • 1
  • 23
  • 35
0

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.

Kjetil S.
  • 3,468
  • 20
  • 22