1

I am trying to concatenate a scalar with array name but not sure how to do. Lets say we have two for loops (one nested inside other) like

for ($i = 0; $i <= 5; $i++) {
    for ($k = 0; $k <=5; $k++) {
       $array[$k] = $k;
    }
}

I want to create 5 arrays with names like @array1, @array2, @array3 etc. The numeric at end of each array represents value of $i when array creation in progress. Is there a way to do it?

2 Answers 2

2

If you mean to create actual variables, for one thing, it's a bad idea, and for another, there is no point. You can simply access a variable without creating or declaring it. It's a bad idea because it is what a hash does, exactly, and with none of the drawbacks.

my %hash;
$hash{array1} = [ 1, 2, 3 ];

There, now you have created an array. To access it, do:

print @{ $hash{array1} };

The hash keys (names) can be created dynamically, just like you want, so it is easy to create 5 different names and assign values to them.

for my $i (0 .. 5) {
    push @{ $hash{"array$i"} }, "foo";
}
Sign up to request clarification or add additional context in comments.

Comments

0

You need to add {} and "" to characters, when they are used as variable or array/hash name.

Try this:

for ($i = 0; $i <= 5; $i++){
    for ($k = 0; $k <=5; $k++){
        ${"array$k"}[$k] = $k;
    } 
}
print "array5[4] = $array5[4]
array5[5] = $array5[5]\n";

2 Comments

Doesn't work with strict. Use hashes instead.
There are called "symbolic references" (forbidden by strict) and should not be used by anyone who has to ask a question about them. Use a proper data structure instead.

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.