perl

Concatenate scalar with array name


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


Solution

  • 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";
    }