blueFish
blueFish

Reputation: 79

Perl: Can I use a variable to name an array?

Can I use a variable to name an array?

For example:

my $input1="AAA";
my $input2="BBB";
my @{$input1};
my @{$input2};

Because $input1=AAA.

So I want to create an array and its name depends on $input1's value.

And finally it will create array @AAA and @BBB.

Is this feasible?

Upvotes: 3

Views: 388

Answers (1)

zdim
zdim

Reputation: 66924

That would need a "symbolic reference," a big no-no for good reasons (also see it in perlfaq7, and for example in this page). It's a dangerous ancient "feature" which is used only very rarely and for very specific purposes.

Instead, use a hash

my %h = ( $input1 => $arrayref1, $input2 => $arrayref2 );

$arrayref is either a reference to a named array, \@ary, or an anonymous array, [LIST]. See about how to create them in perlreftut, and the rest of the tutorial for working with them.

So now when you need an array by a name stored in a a variable it's $h{$input1}, or $h{AAA} (if that's the value of $input1), what returns the array reference that can be de-referenced to access/add elements. See the linked perlreftut.


Note a big difference in how the arrayref is given. If it is a reference to a named array, then any change in that array is reflected in what we get from the hash (and the other way round)

use warnings;
use strict;
use feature 'say';

my $in1 = 'A';
my @ary = 5..7;

my %h = ( $in1 => \@ary );

say $h{$in1}->[0];   #--> 5

$ary[0] = 2;

say $h{$in1}->[0];   #--> 2

$h{$in1}->[-1] = 9;
say "@ary";          #--> 2 6 9 

While if we use an anonymous array, $in1 => [ LIST ], then we get a copy which cannot be changed other than by writing to $h{$in1} directly (unless LIST itself contains references).

If the LIST has references then for an an independent copy one needs a "deep copy."

Upvotes: 4

Related Questions