perl hash issue

Hi All,

#!/usr/local/bin/perl
my %hash = (
        en => {
                name => "english"
        },
        de => {
                name => "german"
        }
        );


my $lang = "kk";
my @keys_arr = keys %hash;
print "Before the exists condition check the keys are @keys_arr\n";

if( exists $hash{$lang}{name}){
        print "THE Language name is $hash{$lang}{name}\n";
}else{
        print "THE Language is not found \n";
}

@keys_arr = keys %hash;
print "After the exists condition check the keys are @keys_arr\n";

Now when i print the array , why does the value kk also occur in the array??

Please let me know if i am missing anything here.
Regards,
Lakshmi
lakshminairAsked:
Who is Participating?
 
kanduraConnect With a Mentor Commented:
That's because when you're saying $hash{kk}{name}, it auto-vivifies $hash{kk} with an empty hashref.
Try writing your if like this:

    if( exists $hash{$lang} ) {
0
 
ITcrowConnect With a Mentor Commented:

if( $hash{$lang}  && $hash{$lang}{name} ) {
        print "THE Language name is $hash{$lang}{name}\n";
}else{
        print "THE Language is not found \n";
}
0
 
rugdogCommented:
or

if( defined $hash{$lang}{name}){
       print "THE Language name is $hash{$lang}{name}\n";
}else{
       print "THE Language is not found \n";
}
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
kanduraCommented:
> if( defined $hash{$lang}{name}){

that also autovivifies $hash{kk}.
0
 
rugdogCommented:
you're right, I missed the my $lang='kk' while testing it and thought it worked
0
 
godspropyCommented:
To get perl not to autovivify the hash you can access the $hash{$lang} as a pointer. This worked in my testing:

if( exists $$hash{$lang}{name}){
0
 
godspropyCommented:
Sorry about that, the above post actually does not find existing values either. However, ITcrow has the proper solution above.
0
 
leitzlerCommented:
You even might have to check them one at a time:

if( exists $hash{$lang} ) {
     if ( exists $hash{$lang}{'name'} ) {
          print "THE Language name is $hash{$lang}{'name'}\n";
     }
}
0
 
ozoCommented:
that is essentialy equivalent to ITcrow's solution

print "THE Language name is $hash{$lang}{name}\n" if exists $hash{$lang} && exists $hash{$lang}{name};
0
All Courses

From novice to tech pro — start learning today.