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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Assigning a hash by reference

Status
Not open for further replies.

audiopro

Programmer
Joined
Apr 1, 2004
Messages
3,165
Location
GB
I have the following code
Code:
my $EMES='$'.$TABLE_NAME[$WHICH_TABLE];
$EMES.='_COMMENT';
$EMES.="{'EMAIL'}";
print "em - $EMES<BR>";
Which produces a hash reference
Code:
em - $CUSTOMERS_COMMENT{'EMAIL'}
I am trying to execute code
Code:
$CUSTOMERS_COMMENT{'EMAIL'}="A Message";
but cannot work out how to assign the hash, using $EMES.
I think I must call $EMES as a reference but what is the syntax?
Code:
$EMES="A Message" # assigns new value,
\$EMES="A Message" # throws a dizzy fit
I know it should be simple but my head hurts


Keith
 
If you are going to build up the variable name in this way you will need eval. Cue ishnid for a reference to his famous FAQ on why you shouldn't do this. Alternative could be:
Code:
my %table_comments;
$table_comments{$TABLE_NAME[$WHICH_TABLE]}->{'EMAIL'} = "A message";

print "em - ", $table_comments{$TABLE_NAME[$WHICH_TABLE]}->{'EMAIL'}, "<BR>";


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]
 
Thanks for that, I wouldn't want the Ishnid monster to vent his wrath in my direction.
I have had a rethink and solved the problem another way. I have a number of MySQL tables and had created a seperate hash for each table, to create form field user notes. The solution was to create only 1 hash and then assign just the key section to the name of the form field. The added bonus is that the code is simplified too.


Keith
 
Glad you got it sorted out. Usually (unless you are working with a *really* primitive language) if you ever find yourself constructing variable names on the fly, it normally means you're doing it wrong and there is a better way to do it. In perl, the better solution usually involves hashes. [smile]

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]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top