Alex
Alex

Reputation: 2040

Perl syntax (replacing 'defined(@array')

Let me start by saying I haven't programmed in Perl in a LONG time.

Currently trying to get some older code to work that relies on defined with an array.

Code (abridged):

# defined outside the file-reading block
my %refPRE;

# line from a file
@c = split();


if (defined @{$refPRE{$c[0]}})
{
    # do stuff
}

Now this won't run like this because of the following error:

Can't use 'defined(@array)' (Maybe you should just omit the defined()?)

Fine, but if I removed the defined then I get the following error:

Can't use an undefined value as an ARRAY reference.

I can see what it's trying to do (if $c[0] is in the $refPRE then do this, else do something else) but I'm not familiar enough with Perl to figure out what the right way to get this to work is. Hoping this is trivial for someone.

Upvotes: 2

Views: 1413

Answers (3)

JGNI
JGNI

Reputation: 4013

Looking at your second error $refPRE{$c[0]} can be undefined so @{ ... } is failing. You can fix this using the undef or opperator // like this.

if (@{ $refPRE{$c[0]} // [] }) { ... }

This checks if $refPRE{$c[0]} is defined and if not returns an empty anonymous array. An empty array is false in an if statement.

Upvotes: 4

simbabque
simbabque

Reputation: 54333

Can't use an undefined value as an ARRAY reference.

This is saying that $refPRE{ $c[0] } is returning undef, and you cannot dereference undef as an array.

@{ undef } # will error

You don't need to deref this at all. If it returns undef, it's false. If it returns anything else, that will (likely) be true.

if ( $refPRE{$c[0]} )
{
   my $foo = @{ $refPRE{$c[0]} };
    # do stuff
}

Upvotes: 3

Alex
Alex

Reputation: 2040

Apparently posting here is all the catalyst I needed...

Switching if (defined @{$refPRE{$c[0]}}) to if ($refPRE{$c[0]}) was sufficient to work! Hopefully this helps someone else who searching for this (specific) problem...

Upvotes: 3

Related Questions