![](/img/trans.png)
[英]How can I elegantly call a Perl subroutine whose name is held in a variable?
[英]How can I elegantly turn user input into a variable name in Perl?
我想使用来自用户的输入来选择要操作的哈希。 目前,我有这个繁琐的代码:
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帖子。
你要
my @hashes;
print "Which hash to work with (1 or 2)? ";
my $which = <>;
chomp $which;
do_something( %{ $hashes[$which] } );
万一你不知道,总是use strict; use warnings;
use strict; use warnings;
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.