2

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?

zdim
  • 64,580
  • 5
  • 52
  • 81
blueFish
  • 69
  • 3
  • Isn't your code already doing what you ask? – n0rd Jun 02 '22 at 00: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](https://perldoc.perl.org/perlreftut) for such situation. – Polar Bear Jun 02 '22 at 01:14

1 Answers1

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

zdim
  • 64,580
  • 5
  • 52
  • 81
  • @blueFish Given a follow-up question I've added a clarification, with a complete example. – zdim Jun 02 '22 at 08:01