如何在Perl中优雅地将用户输入转换为变量名?

时间:2013-05-14 19:21:10

标签: perl command-line-interface user-input control-flow

我想使用来自用户的输入来选择要操作的哈希。目前,我有这个繁琐的代码:

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;

有更优雅的方法吗?我在考虑使用%{"hash$which"},但这似乎不起作用。我想

$which = "hash" . chomp $which;
&do_something( %{"$which"} );

会起作用,但这是最好的方法吗?

感谢您的帮助,特别是因为这是我的第一篇SO帖子。

2 个答案:

答案 0 :(得分:3)

Why it's stupid to use a variable as a variable name

你想要

my @hashes;
print "Which hash to work with (1 or 2)? ";
my $which = <>;
chomp $which;
do_something( %{ $hashes[$which] } );

如果您不知道,请始终使用use strict; use warnings;

答案 1 :(得分:1)

您正在寻找的内容在perl世界中被称为“符号引用”。符号引用的使用是strongly discouraged

为什么不添加另一个间接级别?

my $hash = {
    user_opt1 => {
        foo => 'bar',
    },
    user_opt2 => {
        foo => 'baz',
    },
};