joe
joe

Reputation: 35107

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

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?

Upvotes: 2

Views: 19297

Answers (6)

Bimlesh Sharma
Bimlesh Sharma

Reputation: 306

Try this :

my @tt = map {$_, if $_ == $test_value} keys %a;
print "\n @tt";

Upvotes: 0

Robin Smidsrød
Robin Smidsrød

Reputation: 487

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

Upvotes: 6

Kishore Roy
Kishore Roy

Reputation: 1

As this is an array of hashes you first have to go to that array and then access the element by its key value.

print "${@{$h{LMN}{xyz}{c}}[2]}{Number}";

Upvotes: 0

Crenshaw
Crenshaw

Reputation: 103

Readable? :)

This oneliner will give you the same thing:

defined $a{$testvalue} and print $a{$testvalue}; 

Upvotes: -2

Vagnerr
Vagnerr

Reputation: 3007

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 :-)

Upvotes: -1

Chris Harris
Chris Harris

Reputation: 4745

I think this is what you're looking for:

print $a{$test_value};

Upvotes: 9

Related Questions