You can also try:

   foreach (qw(var1 var2 var3 var4))
   {
           eval ('print "'.$_.' -> $'.$_.'\n"');
   }

Either way works.

Tal Cohen

PS

>... but it printed nothing.

Did you assign a value to $var1, $var2, $var3, $var4? :)

-----Original Message-----
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED]
On Behalf Of Richard Morse
Sent: Wednesday, September 01, 2004 11:28 AM
To: Palit, Nilanjan
Cc: <[EMAIL PROTECTED]>
Subject: Re: [Boston.pm] Interpolating variables

On 1 Sep 2004, at 11:11 AM, Palit, Nilanjan wrote:

> I thought this is possible, but maybe I'm wrong. Ok, here's the issue:
>
> I want to print the values of a bunch of variables so I thought I'll
> take a shortcut and do this:
>
> foreach (qw(var1 var2 var3 var4))
> {
>       print "$_  -> ${$_}\n";
> }
>
> I had thought that interpolating the variable name ("${$_}") would 
> cause
> Perl to interpret the correct variable name & print its value, but it
> printed nothing.
>
> Is my syntax wrong or is this not possible at all? I checked Mr. Camel,
> but did not find anything there on this specifically.

This works fine:

#!/usr/bin/perl

$var1 = 'a';
$var2 = 'b';
$var3 = 'c';

foreach (qw(var1 var2 var3)) {
        print $_ . ' => ' . ${$_} . "\n";
}

Note, however, that you need to make sure the variables are _not_ 
lexical variables, but rather package variables.  Ie, you can't use 
'my' to define the variable.  Also, 'use strict' will prevent this.

HTH,
Ricky

_______________________________________________
Boston-pm mailing list
[EMAIL PROTECTED]
http://mail.pm.org/mailman/listinfo/boston-pm


_______________________________________________
Boston-pm mailing list
[EMAIL PROTECTED]
http://mail.pm.org/mailman/listinfo/boston-pm

Reply via email to