3

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?

2
  • Isn't your code already doing what you ask? Commented Jun 2, 2022 at 0:26
  • How do you intend to use dynamically name defined array if you do not know in advance it's name? Perl has array reference for such situation. Commented Jun 2, 2022 at 1:14

1 Answer 1

4

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."

Sign up to request clarification or add additional context in comments.

1 Comment

@blueFish Given a follow-up question I've added a clarification, with a complete example.

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.