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

Variable name within a variable name? 1

Status
Not open for further replies.

peterv6

Programmer
Sep 10, 2005
70
US
Does anyone know if there is a way to create a variable name that includes the name of another variable? What I'm looking to do is create the name of a counter, that contains the name of what is being counted. Example: I have two messages whose message names are TR001 & XY002. I'm counting requests and replies for each. If possible, I'd like to have a counter name something like this: $var1_requests where $var1 contains the name of the message, like TR001_requests. Would someone mind explaining how to do this, if it is indeed possible?
Thanks....

PETERV
Syracuse, NY &
Boston, MA
 
Yes, it is possible, but you don't want to do it. Unless your language doesn't support any other method, using a variable name like this is always a Really Bad Idea. That's what hashes were invented for.
Code:
#!/usr/bin/perl
use strict;
use warnings;

my %counts;

while (<DATA>) {
   chomp;
   $counts{$_}++;
}

print "$_:\t$counts{$_}\n" foreach (sort keys %counts);

__DATA__
thing1
thing2
thing1
Use the keys of the hash to provide the same effect as changing part of the variable name, but without the downside.

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]
 
It's possible, but highly discouraged for several reasons - use a hash instead with the keys as message names and the values as number of requests.
Code:
%messages = ( 'TR001' => 0,
              'XY002' => 0,
            );

$messages{TR001}++; # increase count for TR001 by one

print $messages{TR001}; # print count for TR001

Using a variable as a variable name is called a symbolic reference. Do a google search and you'll find all the reasons not to use them.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top