onigame
onigame

Reputation: 214

Perl: Quick way to make a list of list references

I find myself doing this construct a lot:

my @listOfLists = ();
foreach (1..$count) {
  my @temporaryList = ();
  push @listOfLists, \@temporaryList;
}

Is there a less typing, one-liner way to do this? Note that this doesn't work:

my @listOfLists = ([]) x $count;

It doesn't work because the individual items are all pointing to the reference to the same empty list.

Upvotes: 1

Views: 83

Answers (1)

choroba
choroba

Reputation: 242113

You can use the anonymous array [...] in the loop:

my @listOfLists;
for (1 .. $count) {
    push @listOfLists, [];
}

for loop can be disguised as a map:

my @listOfLists = map [], 1 .. $count;

which is probably what you wanted to do with x.

Another thing is you often don't need it. Perl will autovivify the array for you when needed:

my @lol;
$lol[2][4] = [ 'a' .. 'z' ];
print $lol[2][4][3];  # d

Upvotes: 6

Related Questions