Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Declare variable via dereference

Status
Not open for further replies.

hamilton123

Technical User
Jun 19, 2007
3
0
0
AT
I have an array of strings @array=("Checkbutton","Label",...) and I want to declare corresponding variables $Checkbutton, $Label automatically.
I tried the declaration my ${$array}, but this gives an error "Can't declare scalar dereference...".
Any suggestions?

Thanks for your help!
 
Whenever you fell you need to create variable names on the fly like this, your design is wrong. Use a hash instead.
Code:
my %form_values;

$form_values{$_} = 0 foreach (@array);

print "Variable: $_\tValue: $form_values{$_}\n" foreach (sort keys @form_values);
or similar. (coded from the hip and untested - no perl on this PC).


Cue ishnid's famous link on the subject...

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
Use a hash like Steve suggests. Using soft references will just lead to problems. If you already have your array a simple way to build it into a hash is using the map function:


Code:
my @array = ("Checkbutton","Label",...);
my %hash = map {$_ => undef} @array;

or something similar. Then you can assign values to the hash keys as needed in your script:

$hash{'Checkbutton'} = 'foo';



------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Thanks very much for your help. I'll try the hash version.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top