Reputation: 527
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?
Thanks
Upvotes: 1
Views: 379
Reputation: 7
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";
array5[4] =
array5[5] = 5
Upvotes: 1
Reputation: 67900
If you mean to create actual variables, for one thing, its a bad idea, and for another, there is no point. You can simply access a variable without creating or declaring it. Its 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";
}
Upvotes: 1