tags:

views:

659

answers:

5

Code:

%a =  ( 1 => "ONE" , 
        2 => "TWO" ,
        3 => " Three", ); 
$test_value = 1 ;

foreach $key (sort(keys %a)) {
    if  ($key == $test_value ) { 
        print $a{$key}; 
    }

}

I just want to achieve the same operation in very short way. Is there any shortcut for this?

+8  A: 

I think this is what you're looking for:

print $a{$test_value};
Chris Harris
if the $a{$test_value} is not defined Wat will be return ?
joe
@Krish: The return value will be `undef`.
Alan Haggai Alavi
you can test: if( exists $a{$test_value} ) { print $a{$test_value}; // will warn if it exists and is null }
Massa
the "exists" keyword was what he was looking for, answer is in the question ;)
castaway
+1  A: 

Assuming that the $test_value would be a variable of some sort you might want something like

if( defined( $a{$test_value} ) ){
    print $a{$test_value};
}

or even

print $a{$test_value} if( defined( $a{$test_value} ) )

depending on how readable you want it :-)

Vagnerr
get rid of all your parenthesis on the last one for the BEST readability.
In this case you probably want to check here if $a{$test_value} is defined - but more generally this could return false if the value was undef. Use exist to check for this case, which will check if the key exists in the hash, not if the value is defined.
Callum
You want to use 'exists', not 'defined' , or autovivification will take place and the value will start to exist.
Kent Fredric
A: 

Readable? :)

This oneliner will give you the same thing:

defined $a{$testvalue} and print $a{$testvalue};
Crenshaw
You want to use 'exists', not 'defined' , or autovivification will take place and the value will start to exist.
Kent Fredric
No, autovivification only happens when you access nested values. $a{$foo}{$bar} will autovivify $foo even if it doesn't exist, and even if it's only checking for existence/definedness.
nothingmuch
+2  A: 

print $a{$test_value} if exists $a{$test_value};

Robin Smidsrød
A: 
abhishek
Do post a question in the answer field. Instead, delete this and ask a new question separately: http://stackoverflow.com/questions/ask
daxim