如何对我事先不知道名称的多个变量执行替换?
我正在编写一个 Perl 脚本,其中用户在脚本开头添加许多设置变量,所有变量都以 $XX
为前缀,如下所示。 然而,用户设置的变量需要通过一个简短的转换函数来清理它们。
有没有办法在所有带有 $XX
前缀的变量上运行子程序?
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*);
编辑: 我现在尝试使用哈希来完成此操作,按照 Google 上的一些建议:
my %XX;
$XX{var1} = "something 1";
$XX{var2} = "something 2";
$XX{var3} = "something 3";
$XX{var4} = "something 4";
然后我可以使用 for
或 while
循环中的键和值。 但是,如何将循环中的每个变量重新分配给转换后的变量?
再次编辑: 知道了。 这个 for 循环成功处理了所有变量:
for my $key ( keys %XX ) {
$XX{$key} = processVar($XX{$key});
}
不过,我现在肯定会尝试创建一个配置文件,如下所示。 现在我只需要弄清楚:)
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 :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
用户无需编辑源代码并提供奇怪的变量名称,而是使用配置文件。 每个用户都可以获得自己的配置文件。 CPAN 上有几个模块可以处理几乎任何格式的配置文件,我将讨论配置 Perl 的方法《掌握 Perl》一章中的程序。 这肯定比您需要神奇地获取这些变量名称所需的技巧要容易得多。
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.
阅读 MJD 的:
Read MJD's:
就是图个好玩儿。 但不要这样做,这是邪恶的:-)
我的 Perl 有点生疏,所以肯定有一个更短/更干净的版本。
Just for the fun of it. But don't do this it's evil :-)
My Perl is a bit rusty so there surly is a shorter/cleaner version of it.