CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Manipulating arrays by variables

 



yaniv_av
Novice

Dec 30, 2002, 7:05 AM

Post #1 of 3 (366 views)
Manipulating arrays by variables Can't Post

Suppose I have:

@A=(0,1,2);
@tmp=("group","A");

I want to print the array @A by using the variable $tmp[1] (which equal "A" in this example).
I wrote this: print "@$tmp[1]\n";
but it didn't work out.
Why, and how can I do it correctly ?


thodi
stranger

Dec 30, 2002, 9:39 AM

Post #2 of 3 (365 views)
Re: [yaniv_av] Manipulating arrays by variables [In reply to] Can't Post

Try this one:

Code
print "@{$tmp[1]}";



davorg
Thaumaturge / Moderator

Dec 31, 2002, 2:24 AM

Post #3 of 3 (358 views)
Re: [yaniv_av] Manipulating arrays by variables [In reply to] Can't Post

The process of using a variable as the name of another variable is called a "symbolic reference" and it's a very bad idea for many reasons which have been explained very well in these three articles. It suggest you read those before going any further.

In fact symbolic references as such a bad idea that when you put "use strict" at the top of your program (and you really should be doing that) one of the effects is to explicitly prevent you from using symbolic references.

A better way to do things like this is usually to use a hash. In your case I'd do something like this:

Code
my %arrays; 
$arrays{A} = [0, 1, 2];

my @tmp = ('group', 'A');

print @{$arrays{$tmp[1]}};


--
Dave Cross, Perl Hacker, Trainer and Writer
http://www.dave.org.uk/
Get more help at Perl Monks

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives