Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't I reference a (particular) Perl array as I'd expect?

I am attempting to use the following to iterate through an array of arrays:

foreach my $elem ( @{ $mastermap } )
{
    say $elem;
    say $elem[0];
    say Dumper($elem);
}

(All just debug output at this point, not what I actually want to do with the array data.)
The output I’m getting (repeated for each loop iteration) is something like:

ARRAY(0x55dabc740cc0)
Use of uninitialized value in say at test.pl line 39.

$VAR1 = [
          'bob',
          '*',
          '1492',
          '1492',
          'machine acct',
          '/var/bob',
          '/bin/false'
        ];

So $elem is an array (also tried treating it as a hash, which was wrong), and Dumper can output the contents of the array, but $elem[0] is undefined? Please tell me what I’m misunderstanding about arrays (probably quite a bit). In case it helps, $mastermap is (I think) an array of arrays, read in using Text::CSV as follows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

my $mastermap = csv ({ in => $passwd, sep_char => ":", quote_char => "#" });

where $passwd is more or less a copy of /etc/passwd.

>Solution :

$elem[0] tries to access to the 1st item in the array @elem. What you actually want to is to access the 1st item in the array reference $item. The correct syntax to do so is:

$elem->[0]

or

$$elem[0]

You should always add use strict; and use warnings; to the beginning of your Perl scripts/programs. Doing so would have produced the following warning:

Global symbol "@elem" requires explicit package name (did you forget to declare "my @elem"?) at...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading