user2013387
user2013387

Reputation: 203

Error: Can't use an undefined value as an ARRAY reference

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?

Upvotes: 4

Views: 25947

Answers (4)

Pietsnot
Pietsnot

Reputation: 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";}

Upvotes: -1

friedo
friedo

Reputation: 66957

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

if ( not defined $val ) { 
    # do something
}

Upvotes: 5

darch
darch

Reputation: 4311

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
}

Upvotes: 2

jmcneirney
jmcneirney

Reputation: 1384

Use

 use strict;
 use warnings;

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

Upvotes: 1

Related Questions