[英]How can I elegantly turn user input into a variable name in Perl?
I want to use input from the user to pick a hash to operate on. 我想使用来自用户的输入来选择要操作的哈希。 Currently, I have this cumbersome code:
目前,我有这个繁琐的代码:
my ( %hash1, %hash2 );
print "Which hash to work with (1 or 2)? ";
my $which = <>;
chomp $which;
&do_something( %hash1 ) if $which == 1;
&do_something( %hash2 ) if $which == 2;
Is there a more elegant way to do this? 有没有更优雅的方式来做到这一点? I was thinking of using
%{"hash$which"}
, but that doesn't seem to work. 我在考虑使用
%{"hash$which"}
,但这似乎不起作用。 I think 我认为
$which = "hash" . chomp $which;
&do_something( %{"$which"} );
would work, but is that the best way to do it? 会工作,但这是最好的方法吗?
Thanks for the help, especially since this is my first SO post. 感谢您的帮助,特别是因为这是我的第一篇SO帖子。
Why it's stupid to use a variable as a variable name 为什么将变量用作变量名是愚蠢的
You want 你要
my @hashes;
print "Which hash to work with (1 or 2)? ";
my $which = <>;
chomp $which;
do_something( %{ $hashes[$which] } );
Just in case you don't know, always use use strict; use warnings;
万一你不知道,总是
use strict; use warnings;
use strict; use warnings;
. 。
What you are looking for is called a "symbolic reference" in the perl world. 您正在寻找的东西在perl世界中被称为“符号参考”。 The use of symbolic references is strongly discouraged .
强烈 建议不要使用符号引用。
Why not add another level of indirection? 为什么不添加另一个间接级别?
my $hash = {
user_opt1 => {
foo => 'bar',
},
user_opt2 => {
foo => 'baz',
},
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.