Tuesday, February 16, 2010

Perl interview questions Part #7

1) What happens when you return a reference to a private variable?

Answer:
Perl Keeps track of your variables, whether dynamic or otherwise, and dones't free things before you're done using them.

2) How do I sort a hash by the hash value?

Answer:

#!/usr/bin/perl -w
# help sort a hash by the hash 'value', not the 'key'

sub sorthashValueDescendingNum {$grades{$b} <=> ${grades{$a}};

%grades =( student1=>90,
student2=>75,
student3=>76);

print "\n\tGRADES IN ASCENDING NUMERIC ORDER\n";
foreach $key (sort(keys(%grades))){
print "\t\t$grades{$key} \t\t$key\n";
}

print "\n\tGRADES IN DESCENDING NUMERIC ORDER\n";
foreach $key (sorthashValueDescendingNum(keys(%grades))){
print "\t\t$grades{$key} \t\t$key\n";
}

3) How to read file into hash array?

Answer:

The following little snippet of code should do exactly what you want:

open(IN, "filename")

          or die "Couldn't open file for processing: $!";
while (
) {
chomp;
$hash_table{$_} = 0;
}
close IN;

Once you've read in your values, the following single line of code
will print them all out for you:

print "$_ = $hash_table{$_}\n" foreach keys %hash_table;


4) Does Perl have reference type?

Answer:

$str="here we go"  ;  # a scalar variable
$strref = \$str;          # a reference to a scalar

@array=(1..10);       # an array
$arrayref =\@array;  # a reference to an array.

%hash=(key1=>vaule1,
             key2=>value2
);
$rhash-ref =\%hash;


4) How to initialize a hash?

Answer:
my %hash = ();    # initialize a hash
my $hash_ref = {};  # reference to empty hash

5) How to add data into hash?

Answer:
$hash{ 'key' } = 'value';    # hash

    $hash{ $key } = $value;      # hash, using variables

    $href->{ 'key' } = 'value';  # hash ref

    $href->{ $key } = $value;    # hash ref, using variables

    %hash = ( 'key1', 'value1', 'key2', 'value2', 'key3', 'value3' ); # add multiple items

    %hash = (
        key1 => 'value1',
        key2 => 'value2',
        key3 => 'value3',
    );

6) How to copy hash?

Answer:
   my %hash_copy = %hash;  # copy a hash

    my $href_copy = $href;  # copy a hash ref


7)  How to use while or for loop with Hash?


Use each within a while loop. Note that each iterates over entries in an apparently random order, but that order is guaranteed to be the same for the functions keys and values.

    while ( my ($key, $value) = each(%hash) ) {
        print "$key => $value\n";
    }


A hash reference would be only slightly different:

    while ( my ($key, $value) = each(%$hash_ref) ) {
        print "$key =>$value\n";
    }

Use keys with a for loop.

    for my $key ( keys %hash ) {
        my $value = $hash{$key};
        print "$key =>$value\n";
    }

8) What's the size of the hash?

Answer:
print "size of hash:  " . keys( %hash ) . ".\n";
 
 
Extra Hash information

No comments:

Post a Comment

Search This Blog