Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re: Using variables in array names

by polypompholyx (Chaplain)
on Aug 05, 2005 at 12:18 UTC ( #481218=note: print w/replies, xml ) Need Help??

in reply to Using variables in array names

Yes, but you probably don't want to do it:

no strict 'refs'; my $point1 = 'valpt'; @$point1 = (1,2,3); # symbolic reference print @valpt;

Or (your specific request):

no strict 'refs'; my $point1 = 'valpt'; eval "\@use_$point1 = (1,2,3)"; print @use_valpt;

For several security and bug-hunting reasons, this is a very bad idea. What you probably want is a hash instead...

my $point1 = 'valpt'; my @array = (1,2,3); $foo{ "use_$point1" } = \@array; # hard reference to array stored in hash %foo print @{ $foo{ 'use_valpt' } }; # dereference arrayref stored in %foo under 'use_valpt' key

You can then access your data by the name chosen in $point1 without worrying about creating global variables all over the place. Have a look at perlref.

Replies are listed 'Best First'.
Re^2: Using variables in array names
by ikegami (Pope) on Aug 05, 2005 at 13:34 UTC
    Why the eval???
    no strict 'refs'; my $point1 = 'valpt'; eval "\@use_$point1 = (1,2,3)"; print @use_valpt;
    can be written as:
    no strict 'refs'; my $point1 = 'valpt'; @{"use_$point1"} = (1,2,3); print @use_valpt;
      Because I am being particularly dim today. You're quite right: using eval is unnecessary, and may well be like handing a box of matches to a kid whose already playing with petrol. I shouldn't have mentioned it :)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://481218]
and snow settles gently...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (8)
As of 2017-06-22 18:59 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (528 votes). Check out past polls.