Search code examples
perlmultidimensional-arraydefinedautovivification

In Perl, how to use 'defined' function on elements of two-dimensional array?


I am trying to check if an element is defined, using defined function in Perl.

Code :

$mylist[0][0]="wqeqwe";
$mylist[0][1]="afasf";
$mylist[1][0]="lkkjh";

print scalar(@mylist), "\n";

if (defined($mylist[2][0])){print "TRUE\n";}

print scalar(@mylist), "\n";

Output

2
3

Before using defined function, there were two elements in first dimension of @myarray. After using defined function, the number of elements increase to 3.

How to use defined function with out adding new elements ?


Solution

  • First check that the first-level reference exists.

    if ( defined($mylist[2]) && defined($mylist[2][0]) ) {
        print "TRUE\n";
    }
    

    What you've encountered is called autovivification: under some circumstances, Perl creates complex data structures when you use them as if they already existed.