Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

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.

Comment on Re: Using variables in array names
Select or Download Code
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 the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (12)
As of 2015-11-30 16:33 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (777 votes), past polls