0

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.

simbabque
  • 53,749
  • 8
  • 73
  • 136
  • Possible duplicate of [Using a dynamically generated variable name in Perl's strict mode](http://stackoverflow.com/questions/17434333/using-a-dynamically-generated-variable-name-in-perls-strict-mode) – AbhiNickz Jan 17 '17 at 09:30
  • Can you please explain a bit more what you mean by _name_ and what should be _dynamic_ about them? Maybe include an example, even if it has wrong syntax. Right now I think you don't want to do what Abhi believes, but I could be wrong. If it's what he suggests, then don't do it. It will cause you loads of grieve. But we'd need a better explanation to tell. – simbabque Jan 17 '17 at 12:51

3 Answers3

2

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.

simbabque
  • 53,749
  • 8
  • 73
  • 136
Essex Boy
  • 7,565
  • 2
  • 21
  • 24
  • In my practice, I prefer to use arrays of pointers, e.g. $ref->{'name'}->[0]->[1], as you will always pass these things as pointers to functions and will not copy the data contained within - it will save you a lot of memory and performance on huge arrays. – mickvav Jan 20 '17 at 14:40
  • @mickvav $ref->{'name'}->[0]->[1] is exactly the same as $ref->{'name'}[0][1] – Essex Boy Jan 20 '17 at 15:03
0

Example array of array references:

my @x;
$x[$_] = [0..int(rand(5)+1)] for (0..3);
palik
  • 2,425
  • 23
  • 31
0

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 { ...; [ ... ] } ...;
ikegami
  • 367,544
  • 15
  • 269
  • 518