part of variable name is variable, how?

B

bing

The expected output should be:

=====
zero, 0
one, 1
two, 2
=====

This is the code snippet. I know it's not correct. Hence the question
in the subject.

============
$name0 = 0;
$name1 = 1;
$name2 = 2;

%map = (
name0 => 'zero',
name1 => 'one',
name2 => 'two'
);

for ($j=0;$j<=2;$j++)
{
print "$map{name{$j}}, $name{$j}\n";
}
=========

Appreciate any help.

Bing
 
S

surfer dude

While wandering through cyberspace on 1 Aug 2005 13:31:34 -0700, bing
said ...
The expected output should be:

=====
zero, 0
one, 1
two, 2
=====

This is the code snippet. I know it's not correct. Hence the question
in the subject.

============
$name0 = 0;
$name1 = 1;
$name2 = 2;

%map = (
name0 => 'zero',
name1 => 'one',
name2 => 'two'
);

for ($j=0;$j<=2;$j++)
{
print "$map{name{$j}}, $name{$j}\n";
}
=========

Appreciate any help.

Bing

This sounds like a job for "eval"...
 
G

Greg Bacon

: $name0 = 0;
: $name1 = 1;
: $name2 = 2;
:
: %map = (
: name0 => 'zero',
: name1 => 'one',
: name2 => 'two'
: );
:
: for ($j=0;$j<=2;$j++)
: {
: print "$map{name{$j}}, $name{$j}\n";
: }

Change what you're printing, e.g.,

print qq[$map{"name$j"}, name$j\n];

If you're trying to grab the values of $name[0-2], read mjd's series
on why using a variable as a variable name is a bad idea.

http://perl.plover.com/varvarname.html
http://perl.plover.com/varvarname2.html
http://perl.plover.com/varvarname3.html

Consider, for example, grabbing the name from reverse(%map).

Hope this helps,
Greg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,586
Members
45,084
Latest member
HansGeorgi

Latest Threads

Top