perl get variable value ???

hi i have following code

my $a1 = "A" ;
my $a2 = "B" ;
my $a3 = "C" ;

foreach my $k ( 1,2,3 ) 
{
    my $msg = ${a{$k}} # this should be at runtime i am creating variable a1 and assigning it value to msg .
    print "$msg\n" ;
}

above thing is not working !!!
i want when k = 1 msg = "A"

how can i do that ??

-----Post Update-----

i got it working i created array instead of 3 variables .. but still if you can tell me how can do it without array just for curiosity ...

# No "my" here
$a1 = "A" ;
$a2 = "B" ;
$a3 = "C" ;

foreach my $k ( 1,2,3 )
{
    my $msg = ${"a${k}"};
    print "$msg\n" ;
}

This is symbolic reference, and is not typically recommend. It works for variables in the symbol table only, so that means you cannot use this trick for variables that are lexically scoped (i.e. "my").

Are you really sure you want this? I can't think of any reason to advocate such constructs in typical programs except specialized modules that need to mess with the symbol table directly.

I got it working with array.

actually there was a part in code which was repeating. like checking 5,6,7 argument lenght is 1 and then its valid entry so after checking i wanted to print which argument was wrong.

$ARG5 = "ADD ENTRY TO DATABASE" ;
$ARG6 = "ADD ENTRY TO REG FILE" ;
$ARG7 = "SHOW DEBUG MSG" ;

foreach $k in ( 5,6,7) 
{ 
     if ...
     {
      } else 
      { 
             print ${"ARG$k"} entry invalid\n" ;      
       }
}
 
so i created array 

@ARG = ( undef ,undef, ..., "ADD ENTRY TO REG FILE",...) ;

zedex,

what you want to do is use a hash.

Assuming the rest of your code works:

my %ARG = (
   5 => "ADD ENTRY TO DATABASE",
   6 => "ADD ENTRY TO REG FILE",
   7 => "SHOW DEBUG MSG",
);

foreach $k in (5,6,7) {
{ 
     if ...
     {
      } else 
      { 
             print "$ARG{$k} entry invalid\n" ;      
       }
}

Hashes are a fundamental concept of perl (and other programming languages), you need to read up on them and use them as necessary.

thanks KevinADC

actually i was involved in many things so forgot about simple use of HASH. even though i used hash for this same reason previously.. any ways nice to know how to do it :slight_smile: