1

The question is like this: I have a loop. And while I iterate this loop I want to create a number of arrays with the following names: array1 array2 array3...

I am wondering if there is a way to concatenate these names in perl I tried something like this but I get an error

$i = 0;
while ($i <= 5) {
    @array . $i = ();
    $i++;
}

2 Answers 2

4

Yes, you can do this, but no, you should not do this.

What you should do instead is use an array of references to anonymous arrays:

@arrayrefs = ();
$i = 0;
while ($i <= 5) {
    $arrayrefs[$i] = [];
    $i++;
}

or, more tersely:

@arrayrefs = ([], [], [], [], [], []);

But for completeness' sake . . . you can do this, by using "symbolic references":

$i = 0;
while ($i <= 5) {
    my $name = "array$i";
    @$name = ();
    $i++;
}

(of course, arrays default to the empty array anyway, so this isn't really needed . . .).


By the way, note that it's actually customary to use a for loop rather than a while loop for such simple cases. Either this:

for ($i = 0; $i <= 5; $i++) {
    ...
}

or this:

for $i (0 .. 5) {
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

You want to use hash,

use strict;
use warnings;

my %hash;
for my $i (1 .. 5) {

  $hash{ "array$i" } = [];
}

Long story short: Why it's stupid to use a variable as a variable name

1 Comment

Seems to me an AoA would make far more sense than an HoA here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.