On 3/2/07, Kevin Viel <[EMAIL PROTECTED]> wrote:
Greetings,

   I have been struggling with this one for a while.  How can I create a
variable name composed of two or more variables?  I suspect I have to I
have to use a reference:

my $var1 = "part" ;
my $var2 = "2"    ;

my $compound = $var1_$var2 ;
snip

Generally it is a mistake to try to do this.  There is most likely a
better/simpler way to achieve what you are trying to do.  Look more
closely at the data structures available to you (hashes, arrays, and
combinations thereof).  A good starting point is perldoc perldsc or
the online version http://perldoc.perl.org/perldsc.html.  If you
explain why you want to do this to the list we may be able to point
you in the right direction.

But to answer your question (though I hope you choose a better
solution to your problem) you can use the string variant of the eval
function:

#!/usr/bin/perl

use strict;

my $part_2 = "Not a good idea";
my $var1 = "part";
my $var2 = "2";
my $compound = eval "\$${var1}_$var2";

print "$compound\n";

There are three important things to note about this:
1. it is a really bad idea
2. the first $ must be escaped to avoid the first evaluation (the
interpolation into the string)
3. $var1 must be in the form of ${var1} because $var1_ is a valid variable name

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to