blueblue has asked for the wisdom of the Perl Monks concerning the following question:

Hi, So what I am trying to do is print the values from a hash based on user input. So the user input needs to match the key in order to print the associated value. so I was thinking it would go something like this:

use strict; use warnings; my %words = ('hello' => 'world'); print 'type a word: ' chomp(my $inData = <>); if($inData eq (keys %words){ print 'value: ', values %words; }
I looking for others ways to approach this, any input would be a lot of help thanks!

Replies are listed 'Best First'.
Re: Getting values from a Hash from user input
by GrandFather (Saint) on Nov 21, 2013 at 20:31 UTC
    if (exists $words{$inData}) {

    See exists.

    True laziness is hard work
Re: Getting values from a Hash from user input
by Kenosis (Priest) on Nov 21, 2013 at 21:10 UTC

    Another way is to use Perl's defined-or operator (//):

    use strict; use warnings; my %words = ( 'hello' => 'world' ); print 'type a word: '; chomp( my $inData = <> ); print $words{$inData} // "Key '$inData' doesn't exist.\n";

    If the key's defined, it's associated value will be printed, otherwise the 'default' string will be printed.

    Hope this helps!

    Edit: //= -> //. Thank you, Eily.

      The defined-or operator is just //. $lvalue //= "value"; actually means $lvalue = "value" unless defined $lvalue;. This means that you actually write "Key '$inData' doesn't exist.\n" in the hash :

      use Data::Dumper; my %words = ( 'hello' => 'world' ); print 'type a word: '; chomp( my $inData = <> ); print $words{$inData} //= "Key '$inData' doesn't exist.\n"; print Dumper \%words;
      type a word: Bonjour Key 'Bonjour' doesn't exist. $VAR1 = { 'hello' => 'world', 'Bonjour' => 'Key \'Bonjour\' doesn\'t exist. ' };
      You meant print $words{$inData} // "Key '$inData' doesn't exist.\n"; which works fine as long as undef isn't a valid value.

        Thanks for this catch! Corrected...

Re: Getting values from a Hash from user input
by blueblue (Initiate) on Nov 22, 2013 at 14:46 UTC

    Thanks for the help guys, appreciate it.