in reply to Can't use an undefined value as an ARRAY reference at ./test.pl line 14.
As others have pointed out, your problem is you are asking Perl to dereference a reference to a variable that has not been defined.
This demonstrates one of the benefits of using full deference syntax rather than omitting the optional braces:
Why better ? Besides being more readable, the full syntax allows you to put expressions in the dereference, so that in your case you could do:%{ $href } # better than %$href @{ $aref } # better than @$aref
if ( scalar @{ $lib || [] } ) { ... }
Including this because I did just get bitten by it recently:
Also, be cautious of using scalar to test whether an array is populated. If you need to know whether there are non-empty values in the array, scalar can trip you up.
If you want to count only non-empty elements in your array, filter for them using grep:$ perl -Mstrict -E 'my $aref = [ "", undef ]; say scalar @{ $aref || [ +] } ? "True" : "False";' True
Hope this helps!$ perl -Mstrict -E 'my $aref = [ "", undef ]; say scalar ( grep { leng +th $_ } @{ $aref || [] } ) ? "True" : "False";' False
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Can't use an undefined value as an ARRAY reference at ./test.pl line 14.
by mpersico (Monk) on Oct 28, 2016 at 14:26 UTC |