Search code examples
perlcommand-line-interfaceuser-inputcontrol-flow

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. 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.


Solution

  • 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;.