Monday, February 15, 2010

Perl interview questions Part #1

1) How do you know the reference of a variable whether it is a reference, scaller, hash or array?


Answer:    Perl provides the ref() function so that you can check the reference type before dereferencing a reference.


If the referenced object has been blessed into a package, then that package name is returned instead. You can think of ref() as a typeof() operator.

e.g.
if (ref($r) eq "HASH") {
print "r is a reference to a hash.\n";
}
if (!ref($r)) {
print "r is not a reference at all.\n";
}


2) What is the difference between "chop" and "chomp" function?
Answer:
"Chop" function removes the last character completely from the scaler.
"Chomp" function removes the last character if it is newline. By default, chomp 
use the current define $INPUT_RECORD_SEPARATOR $/( default value 'n' ).

3) Print this array @not_sort_list in reversed case-insensitive order
Answer:
@sort_list = sort {lc($a) cmp lc($b)} @not_sort_list;

lc function convert all character into lower case

4) What is '->' in Perl?
Answer:
It's a symbolic link to link one file name to a new name.
e.g. file1->file2, vi file1 ; you are really read the file2

5) How do you create a directory if not there?
Answer:
use strict;
my $path = "folder1/folder2/folder3";
# need to use forward slashes for perl, even under windows.
my $createdir="mkdir -p $path";
# does mkdir -p work under windows???
if (-d $path)
  {
print "$path exists\n" }
else
  { print "mkdir failed\n" unless
system($createdir) }

No comments:

Post a Comment

Search This Blog