4

I am writing scripts where I have to pass or fail a test case. So I have some value in a variable which is coming out to be undef.

I am checking something like this:

I have a $val in which there are array of hashes. Now I am checking if that array is empty:

if(@$val<=0){do something}

So if that $val = undef, then this throws an error:

Can't use an undefined value as an ARRAY reference

How should I check if my $val is empty?

brian d foy
  • 129,424
  • 31
  • 207
  • 592
user2013387
  • 203
  • 1
  • 3
  • 8

4 Answers4

5

If you want to check if a scalar is undef, use the defined operator.

if ( not defined $val ) { 
    # do something
}
friedo
  • 65,762
  • 16
  • 114
  • 184
2

There's two parts to answering the question you might be asking.

First, unconditionally create the array reference. If you might get passed undef in $val, promote it to an empty array reference in your code with something like $val // [].

Then, check to see if @$val is non-zero. Non-zero-ness indicates that there are elements in the array. Conventionally, this is phrased as a truth test:

unless (@{ $val // [] }) {
    ... # stuff to do if the array is empty
}
darch
  • 4,200
  • 1
  • 20
  • 23
1

Use

 use strict;
 use warnings;

at the top of the file and they'll probably tell you what the problem is.

jmcneirney
  • 1,374
  • 8
  • 23
-1

You could try the "exists" function for this: http://perldoc.perl.org/functions/exists.html

This function checks whether your array reference exists in the array of hashes

    if(exists @$val<=0) {do something}
    else {print "$val is an undefined reference";}