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: Intermediate:
Getting a variable value if you have the variable name in a variable?


New User

May 17, 2007, 11:40 AM

Post #1 of 2 (1246 views)
Getting a variable value if you have the variable name in a variable? Can't Post

I'm sure that topic is almost confusing, so I'll try to keep this simplified as much as possible and get the point across.

I have some scripts that checks for the existence of a couple files and does a require() on those files.

if (-e "")
$LoadedEnv = $TRUE;
if (-e "env.".$gHOSTNAME. ".properties")
require('env.'.$gHOSTNAME. '.properties');
$LoadedEnv = $TRUE;

those env files can be customized based on which box, username, etc the script is being run on. Within those files are definitions for variables based on what that box or user needs defined. Such as:

$SCM_NAS_MOUNT = "Y:\\";
$LOCAL_INSTANCE_ROOT = "D:\\development\\builds"

As you can see by the first set of codes, for each file it finds it needs to load it, in a pre-determined order. is a base file of variables that must be defined (it's also used as a template by some people). After it loads that file, if it finds a hostname based file it'll load that, which may or may not override some of those same variables.
So loads: $SCM_Server_Mount = "Z:\\";
then loads: $SCM_Server_Mount = "K:\\";

So the question is: I need to print the values of these variables to a log file for possible troubleshooting reasons later. But how?

I can parse the files as text and grab them, then just print them out I suppose, but is there a way print out all defined variables without knowing what they might named in order to make it universal? Or if I have an array that contains the names of the variables, can I use that to print the values?

such as:

@VarNames = ("$SCM_Server_Mount", "$SCM_NAS_MOUNT", "$LOCAL_INSTANCE_ROOT");

foreach $varname (@VarNames)
print " The value of $varname is: &getVarValue($varname)\n";

sub getVarValue
local($name) = @_;

return ($val);


Anyone have any thoughts on if that's even possible?


New User

May 21, 2007, 10:18 AM

Post #2 of 2 (1234 views)
Re: [zionvier] Getting a variable value if you have the variable name in a variable? [In reply to] Can't Post

Well I did figure it out and the way to do it is definitely something you normally wouldn't want to do, but perl actually does let you do it.

Assuming the array of variable names I mentioned in my last post, which I actually had to get by parsing those env files as a text file and grabbing each line that starts with $ and has a = in it.

foreach $varname (@VarNames)
$varname = substr($varname,1); #strip off the $ in the string
$val = $$varname;
print "$varname = $val\n";


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives