Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Getting values from a Hash from user input

by Kenosis (Priest)
on Nov 21, 2013 at 21:10 UTC ( #1063809=note: print w/ replies, xml ) Need Help??


in reply to Getting values from a Hash from user input

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.


Comment on Re: Getting values from a Hash from user input
Select or Download Code
Replies are listed 'Best First'.
Re^2: Getting values from a Hash from user input
by Eily (Curate) on Nov 21, 2013 at 21:33 UTC

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

        Thanks for help guys

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1063809]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (8)
As of 2015-07-31 01:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (274 votes), past polls