How can I retrieve a Perl hash value only if its key exists?

18,934

Solution 1

I think this is what you're looking for:

print $a{$test_value};

Solution 2

print $a{$test_value} if exists $a{$test_value};
Share:
18,934
Prasad
Author by

Prasad

I am back

Updated on June 19, 2022

Comments

  • Prasad
    Prasad almost 2 years

    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?