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

Time:10-19

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:

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

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

CodePudding user response:

$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...
  •  Tags:  
  • perl
  • Related