Pankaj Pankaj - 6 months ago 13
Perl Question

to access a specific key-value pair in hash

I want to print only the specific key:pair from the following hash in perl:

1: one
2: two
3: three


and I am using the following statement to print my hash:

foreach (sort keys %hash) {
print "$_ : $hash{$_}";
}


what should the code if I only want to print
1: one
or
2: two
from the hash.

Answer
foreach (sort keys %hash) {
  if ($_ eq 1 ) {
    print "$_ : $hash{$_}";
    last;
  }
}

Using last will cause your loop to exit as soon as condition is met. I hope this will solve your problem.