LOGIN
Sign In or Register
Avatar
Not Registered Yet?

Join Now! It's FREE. Get full access and benefit from this site

Reset My password - Remind Me My username

Username
Password
Remember me
× Perl Script

Perl Interview Questions and Answers

More
3 years 2 months ago - 3 years 2 months ago #2175 by rajeshkumar
rajeshkumar created the topic: Perl Interview Questions and Answers
What line of code is a valid hash literal?
[first => 'John', last => 'Smith']
{first => 'John', last => 'Smith'}
%{'first' => 'John', 'last' => 'Smith'}
(first => 'John', last => 'Smith')
<'first' => 'John', 'last' => 'Smith'>
Answer - {first => 'John', last => 'Smith'}

How do you call a subroutine with a scalar value as an argument?
subname{$scalar};
$subname[$scalar];
$scalar=&subname;
subname($scalar);
$scalar=&subname{};
Answer - subname($scalar);

How can a SQL database be accessed like an object?
By creating a named class
Using Class::DBI
Using a typeglob
By creating a DB method
Using CGI::Persist::DBI
Answer - Using Class::DBI

What do you use to create a class?
A hash
A typeglob
A subroutine
An anonymous hash
A package
Answer - A package

What statement would open a file for both reading and writing?
open( my $fh, '<+', $filename ) or end $!;
open( my $fh, '<>', $filename ) or end $!;
open( my $fh, 'rw', $filename ) or end $!;
open( my $fh, '>>', $filename ) or end $!;
open( my $fh, '+<', $filename ) or end $!;
Answer - open( my $fh, '+<', $filename ) or end $!;

What is the purpose of the $_ variable? It:
holds the current error message.
is the default input and pattern matching variable.
contains the current input line number of the filehandle that was last read.
contains the current process ID.
is the input record separator.
Answer - contains the current input line number of the filehandle that was last read.

What regular expression matches lines beginning with an integer followed by a period and a space character?
^[0-9]*\.[ ]
^\d+\.[ ]
^\n.\s
^[0-9]\.\s
^\d\.\s
Answer - ^\d\.\s

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';

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);

How do I do fill_in_the_blank for each file in a directory?
Here's code that just prints a listing of every file in the current directory:
#!/usr/bin/perl -w
opendir(DIR, ".");
@files = readdir(DIR);
closedir(DIR);
foreach $file (@files) {
print "$file\n";
}

How do I generate a list of all .html files in a directory?
Here's a snippet of code that just prints a listing of every file in the current directory that ends with the extension .html:
#!/usr/bin/perl -w
opendir(DIR, ".");
@files = grep(/\.html$/,readdir(DIR));
closedir(DIR);
foreach $file (@files) {
print "$file\n";
}

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.

Why should I 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

How to read from a pipeline with Perl
Example 1:

To run the date command from a Perl program, and read the output
of the command, all you need are a few lines of code like this:

open(DATE, "date|");
$theDate = <DATE>;
close(DATE);

The open() function runs the external date command, then opens
a file handle DATE to the output of the date command.

Next, the output of the date command is read into
the variable $theDate through the file handle DATE.

Example 2:

The following code runs the "ps -f" command, and reads the output:

open(PS_F, "ps -f|");
while (<PS_F>) {
($uid,$pid,$ppid,$restOfLine) = split;
# do whatever I want with the variables here ...
}
close(PS_F);

How do you find the length of an array?
$@array

How do I read command-line arguments with Perl?

With Perl, command-line arguments are stored in the array named @ARGV.
$ARGV[0] contains the first argument, $ARGV[1] contains the second argument, etc.
$#ARGV is the subscript of the last element of the @ARGV array, so the number of arguments on the command line is $#ARGV + 1.
Here's a simple program:
#!/usr/bin/perl

$numArgs = $#ARGV + 1;
print "thanks, you gave me $numArgs command-line arguments.\n";
foreach $argnum (0 .. $#ARGV) {
print "$ARGV[$argnum]\n";
}

How many ways can we express string in Perl?
Many. For example 'this is a string' can be expressed in:
"this is a string"
qq/this is a string like double-quoted string/
qq^this is a string like double-quoted string^
q/this is a string/
q&this is a string&
q(this is a string)

Use and Require

Both the Use and Require statements are used while importing modules.

A require statement imports functions only within their packages. The use statement imports functions with a global scope so that their functions and objects can be accessed directly.

Eg. Require module;
Var = module::method(); //method called with the module reference

Eg: use module;
Var = method(); //method can be called directly

-Use statements are interpreted and are executed during the parsing whereas the require statements are executed during run time thereby supporting dynamic selection of modules.

My and Local

A variable declared with the My statement is scoped within the current block. The variable and its value goes out of scope outside the block whereas a local statement is used to temporarily assign a value to the global variable inside the block. The variable used with local statement still has global accessibility but the value lasts only as long as the control is inside the block.

For and Foreach

The for statement has an initialization, condition check and increment expressions in its body and is used for general iterations performing operations involving a loop. The foreach statement is particularly used to iterate through arrays and runs for the length of the array.

Exec and System

Exec command is used to execute a system command directly which does not return to the calling script unless if the command specified does not exist and System command is used to run a subcommand as part of a Perl script.

i.e The exec command stops the execution of the current process and starts the execution of the new process and does not return back to the stopped process. But the system command, holds the execution of the current process, forks a new process and continues with the execution of the command specified and returns back to the process on hold to continue execution.

You are required to replace a char in a string and store the number of replacements. How would you do that?

#!usr/bin/perl
use strict;
use warnings;
my $mainstring="APerlAReplAFunction";
my $count = ($mainstring =~ tr/A//);
print "There are $count As in the given string\n";
print $mainstring;

You want to concatenate strings with Perl. How would you do that?

By using the dot operator which concatenates strings in Perl.
Eg. $string = “My name is”.$name

There are some duplicate entries in an array and you want to remove them. How would you do that?

If duplicates need to be removed, the best way is to use a hash.
Eg:

sub uniqueentr {
return keys %{{ map { $_ => 1 } @_ }};
}
@array1 = ("tea","coffee","tea","cola”,"coffee");
print join(" ", @array1), "\n";
print join(" ", uniqueentr(@array1)), "\n";

What is the use of command "use strict"?

Use strict command calls the strict pragma and is used to force checks on definition and usage of variables, references and other barewords used in the script. If unsafe or ambiguous statements are used, this command stops the execution of the script instead of just providing warnings.

Explain the arguments for Perl Interpreter.

-a - automatically splits a group of input files
-c - checks the syntax of the script without executing it
-d - invokes the PERL debugger after the script is compiled
-d:module - script is compiled and control is transferred to the module specified.
-d - The command line is interpreted as single line script
-S - uses the $PATH env variable to locate the script
-T - switches on Taint mode
-v - prints the version and path level of the interpreter
-w - prints warnings

What is the use of following?

i.) –w
When used gives out warnings about the possible interpretation errors in the script.

ii.) Strict
Strict is a pragma which is used to force checks on the definition and usage of variables, references and other barewords used in the script. This can be invoked using the use strict command. If there are any unsafe or ambiguous commands in the script, this pragma stops the execution of the script instead of just giving warnings.

iii.) -T.
When used, switches on taint checking which forces Perl to check the origin of variables where outside variables cannot be used in system calls and subshell executions.

Explain different types of Perl Operators.

-Arithmetic operators, +, - ,* etc
-Assignment operators: += , -+, *= etc
-Increment/ decrement operators: ++, --
-String concatenation: ‘.’ operator
-comparison operators: ==, !=, >, < , >= etc
-Logical operators: &&, ||, !

You want to add two arrays together. How would you do that?

@sumarray = (@arr1,@arr2);
We can also use the push function to accomplish the same.

You want to empty an array. How would you do that?

-by setting its length to any –ve number, generally -1
-by assigning null list

You want to read command-line arguements with Perl. How would you do that?

In Perl, command line arguments are stored in an array @ARGV. Hence $ARGV[0] gives the first argument $ARGV[1] gives the second argument and so on. $#ARGV is the subscript of the last element of the @ARGV array, so the number of arguments on the command line is $#ARGV + 1.

You want to print the contents of an entire array. How would you do that?

Step 1: Get the size of the array using the scalar context on the array. Eg. @array = (1,2,3);
print ; "Size: ",scalar @array,"\n";
Step 2: Iterate through the array using a for loop and print each item.

Which functions in Perl allows you to include a module file or a module and what is the difference between them?

“use”

1. The method is used only for the modules (only to include .pm type file)

2. The included objects are verified at the time of compilation.

3. We don’t need to specify the file extension.

4. loads the module at compile time.

“require”

1. The method is used for both libraries and modules.

2. The included objects are verified at the run time.

3. We need to specify the file Extension.

4. Loads at run-time.

suppose we have a module file as “Module.pm”

use Module;

or

require “Module.pm”;

(will do the same)

Regards,
Rajesh Kumar
Twitt me @ twitter.com/RajeshKumarIn

Please Log in to join the conversation.

Time to create page: 0.238 seconds