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

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

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



Dec 30, 2002, 7:05 AM

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

Suppose I have:


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 ?


Dec 30, 2002, 9:39 AM

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

Try this one:

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

Thaumaturge / Moderator

Dec 31, 2002, 2:24 AM

Post #3 of 3 (410 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:

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

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

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

Dave Cross, Perl Hacker, Trainer and Writer
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