I’m working on a Perl script where the user adds a number of set variables at the beginning of the script, all prefixed with $XX, as seen below. The user-set variables, however, need to go through a short transformation function to clean them up.
Is there a way to run the sub on all the variables with the $XX prefix?
my $XXvar1 = "something";
my $XXvar2 = "something";
my $XXvar3 = "something";
my $XXvar4 = "something";
sub processVar {
my $fixVar = $_[0];
# Do stuff
return $fixVar;
}
# This obviously doesn't work. Use some kind of loop or something? How...
$XXvar* = processVar($XXvar*);
Edit:
I’m trying to do this now with a hash, as per some suggestions on Google:
my %XX;
$XX{var1} = "something 1";
$XX{var2} = "something 2";
$XX{var3} = "something 3";
$XX{var4} = "something 4";
I can then work with the keys and values in for or while loops. However, how can I reassign each variable to the transformed one in the loop?
Edit again:
Got it. This for loop processes all the variables successfully:
for my $key ( keys %XX ) {
$XX{$key} = processVar($XX{$key});
}
I’m definitely going to try to make a configuration file now, though, as suggested below. Now I just have to figure that out 🙂
Instead of users editing the source and providing odd variable names, use a configuration file instead. Every user can get his own configuration file. There are several modules on CPAN to handle configuration files of just about any format, and I talk about ways to configure Perl programs in a chapter of Mastering Perl. It’s certainly a lot easier than the tricks you’d need to do to magically pick up these variable names.