Top Most Perl Interview Questions Part – 4
1.What is Perl?
Perl is an interpreted high-level programming language developed by Larry Wall
2.What is Perl one-liner?
There are two ways a Perl script can be run: –from a command line,called one-liner,that means you type and execute immediately on the command line.You’ll need the -e option to start like “C:\ %gt perl -e “print \”Hello\”;”.One-liner doesn’t mean one Perl statement.One-liner may contain many statements in one line.–from a script file,called Perl program.
3.What happens when you return a reference to a private variable?
Perl keeps track of your variables,whether dynamic or otherwise,and doesn’t free things before you’re done using them.
4.How to turn on Perl warnings?Why is that important?
Perl is very forgiving of strange and sometimes wrong code,which can mean hours spent searching for bugs and weird results.Turning on warnings helps uncover common mistakes and strange places and save a lot of debugging time in the long run.
There are various ways of turning on Perl warnings: For Perl one-liner,use -w option on the command line.On Unix or Windows,use the -w option in the shebang line (The first # line in the script).Note: Windows Perl interpreter may not require it.For other systems,choose compiler warnings,or check compiler documentation.
5.What are scalar data and scalar variables?
Perl has a flexible concept of data types.Scalar means a single thing,like a number or string.So the Java concept of int,float,double and string equals to Perl\’s scalar in concept and the numbers and strings are exchangeable.Scalar variable is a Perl variable that is used to store scalar data.It uses a dollar sign $ and followed by one or more alphanumeric characters or underscores.It is case sensitive.
6.Why aren’t Perl’s patterns regular expressions?
Because Perl patterns have back references.A regular expression by definition must be able to determine the next state in the finite automaton without requiring any extra memory to keep around previous state.A pattern /([ab]+)c\1/ requires the state machine to remember old states,and thus disqualifies such patterns as being regular expressions in the classic sense of the term.
7.What is Perl one-liner?What does Perl do if you try to exploit the execve(2) race involving setuid scripts?
Sends mail to root and exits.It has been said that all programs advance to the point of being able to automatically read mail.While not quite at that point (well,without having a module loaded),Perl does at least automatically send it.
8.How do I do < fill-in-the-blank > for each element in a hash?
Here’s a simple technique to process each element in a hash: #!/usr/bin/perl -w %days = ( ‘Sun’ =>’Sunday’,’Mon’ => ‘Monday’,’Tue’ => ‘Tuesday’,’Wed’ => ‘Wednesday’,’Thu’ => ‘Thursday’,’Fri’ => ‘Friday’,’Sat’ => ‘Saturday’ ); foreach $key (sort keys %days) { print “The long name for $key is $days{$key}.\n”; }
9.How do you print out the next line from a filehandle with all its bytes reversed?
print scalar reverse scalar Surprisingly enough,you have to put both the reverse and the into scalar context separately for this to work.
10.How do I send e-mail from a Perl/CGI program on a Unix system?
Sending e-mail from a Perl/CGI program on a Unix computer system is usually pretty simple.Most Perl programs directly invoke the Unix sendmail program.We’ll go through a quick example here.
Assuming that you’ve already have e-mail information you need,such as the send-to address and subject,you can use these next steps to generate and send the e-mail message: # the rest of your program is up here …open(MAIL,”|/usr/lib/sendmail -t”); print MAIL
“To: $sendToAddress\n”; print MAIL “From: $myEmailAddress\n”; print MAIL “Subject: $subject\n”; print MAIL “This is the message body.\n”; print MAIL “Put your message here in the body.\n”; close (MAIL);
11.How do I set environment variables in Perl programs?
you can just do something like this: $path = $ENV{‘PATH’}; As you may remember,”%ENV” is a special hash in Perl that contains the value of all your environment variables.
Because %ENV is a hash,you can set environment variables just as you’d set the value of any Perl hash variable.Here’s how you can set your PATH variable to make sure the following four directories are in your path:: $ENV{‘PATH’} = ‘/bin:/usr/bin:/usr/local/bin:/home/yourname/bin’;
12.How to open and read data files with Perl?
Data files are opened in Perl using the open() function.When you open a data file,all you have to do is specify (a) a file handle and (b) the name of the file you want to read from.As an example,suppose you need to read some data from a file named
“checkbook.txt”.Here’s a simple open statement that opens the checkbook file for read access: open (CHECKBOOK,”checkbook.txt”); In this example,the name “CHECKBOOK” is the file handle that you’ll use later when reading from the checkbook.txt data file.
Any time you want to read data from the checkbook file,just use the file handle named “CHECKBOOK”.Now that we’ve opened the checkbook file,we’d like to be able to read what’s in it.Here’s how to read one line of data from the checkbook file: $record = < CHECKBOOK > ;
After this statement is executed,the variable $record contains the contents of the first line of the checkbook file.The “<>” symbol is called the line reading operator.To print every record of information from the checkbook file open (CHECKBOOK,”checkbook.txt”) || die “couldn’t open the file!”; while ($record = < CHECKBOOK >) { print $record; } close(CHECKBOOK);
13.Why should we use the -w argument with my Perl programs?
Many Perl developers use the -w option of the interpreter,especially during the development stages of an application.This warning option turns on many warning messages that can help you understand and debug your applications.
To use this option on Unix systems,just include it on the first line of the program,like this: #!/usr/bin/perl -w If you develop Perl apps on a DOS/Windows computer,and you’re creating a program named myApp.pl,you can turn on the warning messages when you run your program like this: perl -w myApp.pl
14.How do you print out the next line from a file handle with all its bytes reversed?
print scalar reverse scalar Surprisingly enough,you have to put both the reverse and the into scalar context separately for this to work.
15.Why is it hard to call this function: sub y { “because” }
Because y is a kind of quoting operator.The y/// operator is the sed-savvy synonym for tr///.That means y(3) would be like tr(),which would be looking for a second string,as in tr/a-z/A-Z/,tr(a-z)(A-Z),or tr[a-z][A-Z].
16.What does `$result = f() ..g()’ really return?
False so long as f() returns false,after which it returns true until g() returns true,and then starts the cycle again.This is scalar not list context,so we have the bistable flip-flop range operator famous in parsing of mail messages,as in `$in_body = /^$/ ..eof()’.Except for the first time f() returns true,g() is entirely ignored,and f() will be ignored while g() later when g() is evaluated.
Double dot is the inclusive range operator,f() and g() will both be evaluated on the same record.If you don’t want that to happen,the exclusive range operator,triple dots,can be used instead.For extra credit,describe this: $bingo = ( a() ..b() ) …( c() ..d() );
17.Why does Perl not have overloaded functions?
Because you can inspect the argument count,return context,and object types all by yourself.In Perl,the number of arguments is trivially available to a function via the scalar sense of @_,the return context via wantarray(),and the types of the arguments via ref() if they’re references and simple pattern matching like /^\d+$/ otherwise.In languages like C++ where you can’t do this,you simply must resort to overloading of functions.
18.What does `new $cur->{LINK}’ do? (Assume the current package has no new() function of its own.)
$cur->new()->{LINK} The indirect object syntax only has a single token lookahead.That means if new() is a method,it only grabs the very next token,not the entire following expression.This is why `new $obj[23] arg’ does’t work,as well as why `print $fh[23] “stuff\n”‘ does’t work.
Mixing notations between the OO and IO notations is perilous.If you always use arrow syntax for method calls,and nothing else,you’ll not be surprised.
19.How to read file into hash array?
open(IN,” or die “Couldn’t open file for processing: $!”; while () { chomp; $hash_table{$_} = 0; } close IN; print “$_ = $hash_table{$_}\n” foreach keys %hash_table;
20.Does Perl have reference type?
Yes.Perl can make a scalar or hash type reference by using backslash operator.For example: $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 Note that the reference itself is a scalar.
21.Assume that $ref refers to a scalar,an array,a hash or to some nested data structure.Explain the following statements:
1.$$ref; # returns a scalar
2.$$ref[0]; # returns the first element of that array
3.$ref- > [0]; # returns the first element of that array
4.@$ref; # returns the contents of that array,or number of elements,in scalar context
5.$$ref; # returns the last index in that array
6.$ref- > [0][5]; # returns the sixth element in the first row
7.@{$ref- > {key}} # returns the contents of the array that is the value of the key “key”
22.What value is returned by a lone `return;’ statement?
The undefined value in scalar context,and the empty list value () in list context.This way functions that wish to return failure can just use a simple return without worrying about the context in which they were called.
23.What’s the difference between /^Foo/s and /^Foo/?
The second would match Foo other than at the start of the record if $
* were set.The deprecated $
* flag does double duty,filling the roles of both /s and /m.By using /s,you suppress any settings of that spooky variable,and force your carets and dollars to match only at the ends of the string and not at ends of line as well — just as they would if $
* weren’t set at all.
24.How to dereference a reference?
There are a number of ways to dereference a reference.Using two dollar signs to dereference a scalar.$original = $$strref; Using @ sign to dereference an array.@list = @$arrayref; Similar for hashes.
25.How do I replace every character in a file with a comma?
perl -pi.bak -e ‘s/\t/,/g’ myfile.txt