Sanchita Ghai
Sanchita Ghai

Reputation: 63

Creating 2 D arrays dynamically in Perl

I want to create 2-d arrays dynamically in Perl. I am not sure how to do this exactly.My requirement is something like this-

@a =([0,1,...],[1,0,1..],...)

Also I want to name the references to the internal array dynamically. i.e. I must be able to refer to my internal arrays with my chosen names which I will be allocating dynamically. Can someone please help me on this.

Upvotes: 0

Views: 570

Answers (3)

ikegami
ikegami

Reputation: 385789

You probably have some kind of loop?

for (...) {
    my @subarray = ...;
    push @a, \@subarray;
}

You could also do

for (...) {
    push @a, [ ... ];
}

If it's actually a foreach loop, you could even replace it with a map.

my @a = map { ...; [ ... ] } ...;

Upvotes: 0

Essex Boy
Essex Boy

Reputation: 7950

It sounds like you want a tree/hash of arrays. Use references to achieve this.

Example of hash of array of array:

$ref = {};
$ref->{'name'} = [];
$ref->{'name'}[0] = [];
$ref->{'name'}[0][1] = 3;

This could be dynamic if required. Make sure you initialise what the reference is pointing at.

Upvotes: 2

palik
palik

Reputation: 2863

Example array of array references:

my @x;
$x[$_] = [0..int(rand(5)+1)] for (0..3);

Upvotes: 0

Related Questions