2

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.

2
  • Try: if (exists $refPRE{$c[0]} and (ref $refPRE{$c[0]} eq "ARRAY") and @{$refPRE{$c[0]}}) Commented Feb 26, 2019 at 15:33
  • What you are trying to check for? Commented Feb 26, 2019 at 16:13

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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...

1 Comment

Rubber duck! :D
3

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.