How to get the correct hash value in perl?

Hi,

I have 2 dummy strings below.

I am creating a hash.

@str = qw(karnataka,tamilnadu,bihar,mumbai);
@str1 = qw(bangalore,chennai,patna,panaji);
%hash;
for($i=0;$i<=$#str;$i++) {
push @{ $hash{ $str[$i] } }, $str1[$i];
}
foreach $key (keys %hash) {
print "\n KEY: $key --- @{$hash{$key}} \n";
}

OUTPUT:

 KEY: karnataka,tamilnadu,bihar,mumbai --- bangalore,chennai,patna,panaji

How to print in Key/value pair?

The output should be:

karnataka - Bangalore
tamilnadu -  chennai
bihar       - patna
mumbai   - panaji

If user specifies karnataka as a key it should output as Bangalore.

if(key == karnataka )

{

print Bangalore;

}

How can i do this in perl?

REgards

my %hash = (
        karnataka => 'bangalore',
        tamilnadu => 'chennai',
        bihar => 'bihar',
        maharashtra => 'mumbai'
    );

foreach my $key (keys %hash ) {
        print "$key -- $hash{$key}" . "\n";
    }

You're pushing in the values completely wrong.

@str = qw(karnataka,tamilnadu,bihar,mumbai);

In this case @str contains only one element, "karnataka,tamilnadu,bihar,mumbai", because qw uses whitespace to split the single elements. So either lose the qw, or replace the commas with a single space character. This also applies to @str1 of course.

Sure thanks,

How to get this part?

 if(key == karnataka )

{

print Bangalore;

}

Just read the user input from standard input using the diamond operator ( <> ), and then use that value to access the hash value there ( $hash{key} ). You might want to check if the hash has a value defined for a key first.

#!/usr/bin/perl
my %str = (
        karnataka       =>      'bangalore',
        tamilnadu       =>      'chennai',
        bihar           =>      'patna',
        mumbai          =>      'panaji'
);
while(my($key,$value)= each(%str)) {
        print "$key - $value\n";
}
[user@storage12 ~]$ perl script.pl
mumbai - panaji
tamilnadu - chennai
karnataka - bangalore
bihar - patna