2

I have an array of names, and for each name I wish to create a hash with that as its variable name. Something like this

@list = ('Name1', 'Name2', 'Name3')  

for ($i = 0; $i < scalar @list; $i++) {  
  %(list[$i]);  
}  

Can anyone tell me if this is possible?

Borodin
  • 126,100
  • 9
  • 70
  • 144
user2335015
  • 111
  • 11
  • No the keys and values are added afterwards. First I need to create several Hashes. I will of cause also need to be able to add these using the variable (e.g. $list[x]). – user2335015 Nov 11 '13 at 13:59
  • 2
    The correct way to do this sort of thing is by using a hash, and you have answers to that effect. It *is* possible to do what you describe, but it's a very bad idea. For one thing, how do you know what the names of the hashes that have been created are? If you know what they're called so that you can access them explicitly then you can also declare them explicitly. – Borodin Nov 11 '13 at 14:59
  • Also, `for ($i = 0; $i < scalar @list; $i++) { ... }` is usually written `for my $i (0 .. $#list) { ... }` – Borodin Nov 11 '13 at 15:01
  • Do you have a case where `@list = ('Name1', 'Name2', 'Name3', 'Name1')`? If so, how will that be handled? – Kenosis Nov 11 '13 at 17:22

1 Answers1

2

This will create a hash with keys named after the elements of the provided list:

my @list=('Name1','Name2','Name3');
my %hash;
@hash{@list}=()x3;

Following your comment, here's an update:

So now you can consider them as if you have 3 hash references, and you can populate them as in the following example where we add key and value to hashref Name2:

$hash{'Name2'}->{'key'}='value';
psxls
  • 6,807
  • 6
  • 30
  • 50
  • But it should be the name of the hash, i want to create: %Name1, %Name2, %Name3 and then later to add keys and values somehow again using the index for the list - is that not possible? or should I just make an array of hashes? – user2335015 Nov 11 '13 at 14:04
  • 2
    Oh, OK, now I see. Naming variables after a string is doable using symbolic references, but it's definitely not a good idea. Your question has been already answered, check this for example: http://stackoverflow.com/questions/3871451/in-perl-how-can-i-use-a-string-as-a-variable-name – psxls Nov 11 '13 at 14:06
  • Follow the advise of the Sinan Ünür in the above link. And just create a hash whose keys will be the elements of the array, and their values will be hash references. – psxls Nov 11 '13 at 14:08