Perl Interview Questions & Answers part 3


Q: – How to store more than one value for each key?

Store an array reference in $hash{$key}, and put the values into that array.

Q: – Hashes map keys to values. You have a hash and a value for which you want to find the corresponding key.

Use reverse to create an inverted hash whose values are the original hash's keys and vice versa.
# %LOOKUP maps keys to values
%REVERSE = reverse %LOOKUP;

Q: – The output of the Interest program looks sloppy. How do I control how many digits are displayed?

The easiest way to control the number of decimal digits is to use the printf function

Q: – How to perform an action on each entry in a hash?

Use each with a while loop:

while(($key, $value) = each(%HASH)) {
# do something with $key and $value

Q: – How to print a hash, but neither print "%hash" nor print %hash works?

while ( ($k,$v) = each %hash ) {
print "$k => $v\n";

Q: – Is perl Variables are interpolated inside qq quotes, true or False ?


Q: – How can I count the number of unique elements in an array?

Use a hash. Hashes allow you to do some rather interesting manipulations on arrays quickly and efficiently.

Q: – How to exchange the values of two scalar variables, but don't  use a temporary variable?

Use list assignment to reorder the variables.
($VAR1, $VAR2) = ($VAR2, $VAR1);

Submitted By:-Sameer Dahiya            Email-ID: –