Beefy Boxes and Bandwidth Generously Provided by pair Networks Frank
Don't ask to ask, just ask
 
PerlMonks  

Re: Using variables in array names

by polypompholyx (Hermit)
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
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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://481218]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2013-05-24 03:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best material for plates (tableware) is:









    Results (495 votes), past polls