300+ TOP PERL Interview Questions and Answers

Perl Interview Questions for freshers and experienced :-

1.How many type of variable in perl
Perl has three built in variable types

  • Scalar
  • Array
  • Hash

2.What is the different between array and hash in perl

  • Array is an order list of values position by index.
  • Hash is an unordered list of values position by keys.

3.What is the difference between a list and an array?
A list is a fixed collection of scalars. An array is a variable that holds a variable collection of scalars.

4.what is the difference between use and require in perl

Use :

  1. The method is used only for the modules(only to include .pm type file)
  2. The included objects are varified at the time of compilation.
  3. No Need to give file extension.

Require:

  1. The method is used for both libraries and modules.
  2. The included objects are varified at the run time.
  3. Need to give file Extension.

5.How to Debug Perl Programs
Start perl manually with the perl command and use the -d switch, followed by your script and any arguments you wish to pass to your script:
“perl -d myscript.pl arg1 arg2”

6.What is a subroutine?

  • A subroutine is like a function called upon to execute a task.
  • subroutine is a reusable piece of code.

7.what does this mean ‘$^0’? tell briefly
$^ – Holds the name of the default heading format for the default file handle. Normally, it is equal to the file handle’s name with _TOP appended to it.

8.What is the difference between die and exit in perl?
1) die is used to throw an exception
exit is used to exit the process.
2) die will set the error code based on $! or $? if the exception is uncaught.
exit will set the error code based on its argument.
3) die outputs a message
exit does not.

9.How to merge two array?
@a=(1, 2, 3, 4);
@b=(5, 6, 7, 8);
@c=(@a, @b);
print “@c”;

10.Adding and Removing Elements in Array
Use the following functions to add/remove and elements:

  • push(): adds an element to the end of an array.
  • unshift(): adds an element to the beginning of an array.
  • pop(): removes the last element of an array.
  • shift() : removes the first element of an array.
PERL Interview Questions
PERL Interview Questions and Answers

11.How to get the hash size
%ages = (‘Martin’ => 28, ‘Sharon’ => 35, ‘Rikke’ => 29);
print “Hash size: “,scalar keys %ages,”n”;

12.Add & Remove Elements in Hashes
%ages = (‘Martin’ => 28, ‘Sharon’ => 35, ‘Rikke’ => 29);
# Add one more element in the hash
$age{‘John’} = 40;
# Remove one element from the hash
delete( $age{‘Sharon’} );

13.PERL Conditional Statements
The conditional statements are if and unless

14.Perl supports four main loop types:
While, for, until, foreach

15.There are three loop control keywords: next, last, and redo.
The next keyword skips the remainder of the code block, forcing the loop to proceed to the next value in the loop.
The last keyword ends the loop entirely, skipping the remaining statements in the code block, as well as dropping out of the loop.
The redo keyword reexecutes the code block without reevaluating the conditional statement for the loop.

16.Renaming a file
rename (“/usr/test/file1.txt”, “/usr/test/file2.txt” );

17.Deleting an existing file
unlink (“/usr/test/file1.txt”);

18.Explain tell Function
The first requirement is to find your position within a file, which you do using the tell function:
tell FILEHANDLE
tell

19.Perl Regular Expression
A regular expression is a string of characters that define the pattern
There are three regular expression operators within Perl
Match Regular Expression – m//
Substitute Regular Expression – s///
Transliterate Regular Expression – tr///

20.What is the difference between chop & chomp functions in perl?
chop is used remove last character, chomp function removes only line endings.

21.Email address validation – perl
if ($email_address =~ /^(w¦-¦_¦.)+@((w¦-¦_)+.)+[a-zA-Z]{2,}$/)
{
print “$email_address is valid”;
}
else {
print “$email_address is invalid”;
}

22.Why we use Perl?
1.Perl is a powerful free interpreter.
2.Perl is portable, flexible and easy to learn.

23. Given a file, count the word occurrence (case insensitive)
open(FILE,”filename”);
@array= ;
$wor=”word to be found”;
$count=0;
foreach $line (@array)
{
@arr=split (/s+/,$line);
foreach $word (@arr)
{
if ($word =~ /s*$wors*/i)
$count=$count+1;
}
}
print “The word occurs $count times”;

24.Name all the prefix dereferencer in perl?
The symbol that starts all scalar variables is called a prefix dereferencer. The different types of dereferencer are.
(i) $-Scalar variables
(ii) %-Hash variables
(iii) @-arrays
(iv) &-subroutines
(v) Type globs-*myvar stands for @myvar, %myvar.

What is the Use of Symbolic Reference in PERL?
$name = “bam”;
$$name = 1; # Sets $bam
${$name} = 2; # Sets $bam
${$name x 2} = 3; # Sets $bambam
$name->[0] = 4; # Sets $bam[0]
symbolic reference means using a string as a reference.

25.  What is the difference between for & foreach, exec & system?
Both Perl’s exec() function and system() function execute a system shell command. The big difference is that system() creates a fork process and waits to see if the command succeeds or fails – returning a value. exec() does not return anything, it simply executes the command. Neither of these commands should be used to capture the output of a system call. If your goal is to capture output, you should use the $result = system(PROGRAM); exec(PROGRAM);

26. What is the difference between for & foreach?
Technically, there’s no difference between for and foreach other than some style issues. One is an lias of another. You can do things like this foreach (my $i = 0; $i < 3; ++$i)
{ # normally this is
foreach print $i, “n”;
}
for my $i (0 .. 2)
{ # normally this is for print $i, “n”;}

27.  What is eval in perl?  
eval(EXPR)
eval EXPR
eval BLOCK
EXPR is parsed and executed as if it were a little perl program. It is executed in the context of the current perl program, so that any variable settings, subroutine or format definitions remain afterwards. The value returned is the value of the last expression evaluated, just as with subroutines. If there is a syntax error or runtime error, or a die statement is executed, an undefined value is returned by eval, and $@ is set to the error message. If there was no error, $@ is guaranteed to be a null string. If EXPR is omitted, evaluates $_. The final semicolon, if any, may be omitted from the expression.

28. What’s the difference between grep and map in Perl?
grep returns those elements of the original list that match the expression, while map returns the result of the expression applied to each element of the original list.

29. How to Connect with SqlServer from perl and how to display database table info?
there is a module in perl named DBI – Database independent interface which will be used to connect to any database by using same code. Along with DBI we should use database specific module here it is SQL server. for MSaccess it is DBD::ODBC, for MySQL it is DBD::mysql driver, for integrating oracle with perl use DBD::oracle driver is used. IIy for SQL server there are avilabale many custom defined ppm( perl package manager) like Win32::ODBC, mssql::oleDB etc.so, together with DBI, mssql::oleDB we can access SQL server database from perl. the commands to access database is same for any database.

30. Remove Duplicate Lines from a File
use strict;
use warnings;

my @array=qw(one two three four five six one two six);
print join(” “, uniq(@array)), “n”;

sub uniq {
my %seen = ();
my @r = ();
foreach my $a (@_) {
unless ($seen{$a}) {
push @r, $a;
$seen{$a} = 1;
}
}
return @r;
}

or

my %unique = ();
foreach my $item (@array)
{
$unique{$item} ++;
}
my @myuniquearray = keys %unique;
print “@myuniquearray”;

PERL Interview Questions with Answers

1.  How do you know the reference of a variable whether it is a reference, scaler, hash or
array?
There is a ‘ref’ function that lets you know

2. What is the difference between ‘use’ and ‘require’ function?
Use:
1. the method is used only for modules (only to include .pm type file)
2. the included object are verified at the time of compilation.
3. No Need to give file extension.

Require:
1. The method is used for both libraries (package) and modules
2. The include objects are verified at the run time. 3. Need to give file Extension.

3. What is the use of ‘chomp’ ? what is the difference between ‘chomp’ and ‘chop’?
‘chop’ function only removes the last character completely ‘from the scalar, where as ‘chomp’ function only removes the last character if it is a newline. by default, chomp only removes what is currently defined as the $INPUT_RECORD_SEPARATOR. whenever you call ‘chomp ‘, it checks the value of a special variable ‘$/’. whatever the value of ‘$/’ is eliminated from the scaler. by default the value of ‘$/’ is ‘n’

4. Print this array @arr in reversed case-insensitive order
@solution = sort {lc $a comp lc$b } @arr.

5. What is ‘->’ in Perl?
It is a symbolic link to link one file name to a new name. So let’s say we do it like
file1-> file2, if we read file1, we end up reading file2.

6. How do you check the return code of system call?
System calls “traditionally” returns 9 when successful and 1 when it fails. System
(cmd) or die “Error in command”.

7.  Create directory if not there
Ans:
if (! -s “$temp/engl_2/wf”){
System “mkdir -p $temp/engl_2/wf”;
}
if (! -s “$temp/backup_basedir”) {
system “mkdir -p $temp/backup_basedir”;
}

8. What is the use of -M and -s in the above script?
Ans:
-s means is filename a non-empty file
-M how long since filename modified

9. How to substitute a particular string in a file containing million of record?
perl -p -i.bak -e ‘s/search_str/replace_str/g’ filename

10. I have a variable named $objref which is defined in main package. I want to make it as
a Object of class XYZ. How could I do it?
use XYZ my $objref =XYZ -> new() OR, bless $objref, ‘XYZ’;

11. What is meant by a ‘pack’ in perl?
Pack converts a list into a binary representation. Takes an array or list of values and packs it into a binary structure, returning the string containing the structure it takes a LIST of values and converts it into a string. The string contains a con-catenation of the converted values. Typically, each converted values looks like its machine-level representation. For example, on 32-bit machines a converted integer may be represented by a sequence of 4 bytes.

12. How to implement stack in Perl?
Through push() and shift() function. push adds the element at the last of array and shift() removes from the beginning of an array.

13. What is Grep used for in Perl?

  • Grep is used with regular expression to check if a particular value exists in an array.
  • It returns 0 it the value does not exists, 1 otherwise.

14. How to code in Perl to implement the tail function in UNIX?
You have to maintain a structure to store the line number and the size of the file at that time e.g. 1-10 bytes, 2-18 bytes.. You have a counter to increase the number of lines to find out the number of lines in the file. once you are through the file, you will know the size of the file at any nth line, use ‘sysseek’ to move the file pointer back to that position (last 10) and then tart reading till the end.

15. Explain the difference between ‘my’ and ‘local’ variable scope declarations?
Both of them are used to declare local variables. The variables declared with ‘my’ can live only within the block and cannot gets its visibility inherited functions called within that block, but one defined as ‘local’ can live within the block and have its visibility in the functions called within that block.

16. How do you navigate through an XML documents?
You can use the XML::DOM navigation methods to navigate through an XML::DOM node tree and use the get node value to recover the data. DOM Parser is used when it is need to do node operation. Instead we may use SAX parser if you require simple processing of the xml structure.

17. How to delete an entire directory containing few files in the directory?
rmtree($dir); OR, you can use CPAN module File::Remove Though it sounds like deleting file but it can be used also for deleting directories. &File::Removes::remove (1,$feed-dir,$item_dir);

18. What are the arguments we normally use for Perl Interpreter
-e for Execute
-c to compile
-d to call the debugger on the file specified
-T for traint mode for security/input checking
-W for show all warning mode (or -w to show less warning)

19. What is it meant by ‘$_’?
It is a default variable which holds automatically, a list of arguments passed to the
subroutine within parentheses.

20. How to connect to sql server through Perl?
We use the DBI(Database Independent Interface) module to connect to any
database.
use DBI;
$dh = DBI->connect(“dbi:mysql:database=DBname”,”username”,”password”);
$sth = $dh->prepare(“select name, symbol from table”);
$sth->execute();
while(@row = $sth->fetchrow_array()){
print “name =$row[0].symbol= $row[1];
}

$dh->disconnect

21. What is the purpose of -w, strict and -T?
-w option enables warning
– strict pragma is used when you should declare variables before their use -T is taint mode. TAint mode makes a program more secure by keeping track of arguments which are passed from external source.

22. What is the difference between die and exit?
Die prints out STDERR message in the terminal before exiting the program while exit
just terminate the program without giving any message.
Die also can evaluate expressions before exiting.

23. Where do you go for perl help?
perldoc command with -f option is the best. I also go to search.cpan.org for help.

24. What is the Tk module?
It provides a GUI interface

25. What is your favourite module in Perl?
CGI and DBI.
CGI (Common Gateway Interface) because we do not need to worry about the subtle features of form processing.

26. What is hash in perl?
A hash is like an associative array, in that it is a collection of scalar data, with individual elements selected by some index value which essentially are scalars and called as keys. Each key corresponds to some value. Hashes are represented by % followed by some name.

27. What does ‘qw()’ mean? what’s the use of it?
qw is a construct which quotes words delimited by spaces. use it when you have long list of words that are into quoted or you just do not want to type those quotes as you type out a list of space delimited words. Like @a = qw(1234) which is like
@a=(“1?,”2?,”3?,”4?);

28. What is the difference between Perl and shell script?
Whatever you can do in shell script can be done in Perl.
However

  1. Perl gives you an extended advantage of having enormous library.
  2. You do not need to write everything from scartch.

29. What is stderr() in perl?
Special file handler to standard error in any package.

30. What is a regular expression?
It defines a pattern for a search to match.

31. What is the difference between for and foreach?
Functionally, there is no difference between them.

32. What is the difference between exec and system?
exec runs the given process, switches to its name and never returns while system forks off the given process, waits for its to complete and then return.

33. What is CPAN?
CPAN is comprehensive Perl Archive Network. It’s a repository contains thousands of Perl Modules, source and documentation, and all under GNU/GPL or similar license.
You can go to www.cpan.org for more details. Some Linux distribution provides a till names ‘cpan; which you can install packages directly from cpan.

34. What does this symbol mean ‘->’?
In Perl it is an infix dereference operator. For array subscript, or a hash key, or a subroutine, then its must be a reference. Can be used as method invocation.

35. What is a DataHash()
In Win32::ODBC,  DataHash() function is used to get the data fetched through the sql statement in a hash format.

36. What is the difference between C and Perl?
make up

37. Perl regular exp are greedy. what is it mean by that?
It tries to match the longest string possible.

38. What does the world ‘&my variable’ mean?
&myvariable is calling a sub-routine. & is used to indentify a subroutine.

39. What is it meant by @ISA, @EXPORT, @EXPORT_OK?
@ISA -> each package has its own @ISA array. This array keeps track of classes it is inheriting.
Ex:
package child;
@ISA=(parent class);
@EXPORT this array stores the subroutines to be exported from a module.
@EXPORT_OK this array stores the subroutines to be exported only on request.

40. What package you use to create windows services?
use Win32::OLE.

41. How to start Perl in interactive mode?
perl -e -d 1 PerlConsole.

42. How do I set environment variables in Perl programs?
You can just do something like this: $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/your name/bin’.

43. What is the difference between C++ and Perl?
Perl can have objects whose data cannot be accessed outside its class, but C++ cannot. Perl can use closures with unreachable private data as objects, and C++ doesn’t support closures. Furthermore, C++ does support pointer arithmetic via `int *ip =(int*)&object’, allowing you do look all over the object. Perl doesn’t have pointer arithmetic. It also doesn’t allow `#define private public’ to change access rights to foreign objects. On the other hand, once you start poking around in /dev/mem, no one is safe.

44. 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 = ; 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 = ) {
print $record;
}
close(CHECKBOOK);

45. How do i do fill_in_the_blank for each file in a directory?
#!/usr/bin/perl –w
opendir(DIR, “.”);
@files = readdir(DIR);
closedir(DIR);
foreach $file (@files)
{
print “$filen”;
}

46. How do I generate a list of all .html files in a directory
Here is a snippet of code that just prints a listing of every file in teh current directory.
That ends with the entension
#!/usr/bin/perl –w
opendir(DIR, “.”);
@files  = grep(/.html$/, readdir(DIR));
closedir(DIR);
foreach $file (@files) { print “$filen”; }

47. What is Perl one-liner?
There are two ways a Perl script can be run: –from a command line, called oneliner, 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.

48. Assume both a local($var) and a my($var) exist, what’s the difference between ${var}
and ${“var”}?
${var} is the lexical variable $var, and ${“var”} is the dynamic variable $var. Note that because the second is a symbol table lookup, it is disallowed under `use strict “refs”‘. The words global, local, package, symbol table, and dynamic all refer to the kind of variables that local() affects, whereas the other sort, those governed by my(), are variously knows as private, lexical, or scoped variable.

49. 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

50. 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.

51. Assuming $_ contains HTML, which of the following substitutions will remove all tags in it?
You can’t do that. If it weren’t for HTML comments, improperly formatted HTML, and tags with interesting data like , you could do this. Alas, you cannot. It takes a lot more smarts, and quite frankly, a real parser.

52. What is the output of the following Perl program?
$p1 = “prog1.java”;
$p1 =~ s/(.*).java/$1.cpp/;
print “$p1n”;
prog1.cpp

53. Why aren’t Perl’s patterns regular expressions?
Because Perl patterns has backreferences. 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]+)c1/ requires the state machine to remember old states, and thus disqualifies such patterns as being regular expressions in the classic sense of the term.

54. 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.

55. How do I do 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”;
}

56. How do I sort a hash by the hash key?
Ans:. Suppose we have a class of five students. Their names are kim, al, rocky, chrisy, and jane. Here’s a test program that prints the contents of the grades hash, sorted by student name:
#!/usr/bin/perl –w
%grades = ( kim => 96, al => 63, rocky => 87, chrisy => 96, jane => 79, );
print “ntGRADES SORTED BY STUDENT NAME:n”;
foreach $key (sort (keys(%grades))) {
print “tt$key tt$grades{$key}n”;
}

The output of this
program looks like this: GRADES SORTED BY STUDENT NAME: al 63 chrisy 96 jane
79 kim 96 rocky 87

57. 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 in to scalar context separately for this to work.

58. 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: $sendToAddressn”;
print MAIL “From: $myEmailAddressn”;
print MAIL “Subject: $subjectn”;
print MAIL “This is the message body.n”;
print MAIL “Put your message here in the body.n”;
close (MAIL);

59. How to read from a pipeline with Perl?
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 = ;
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 (){
($uid,$pid,$ppid,$restOfLine) = split; # do whatever I want with the variables here …
}
close(PS_F);

60. Why is it hard to call this function: sub y { “because” }
Ans. 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].

61. 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.

62. What does read() return at end of file?
0. A defined (but false) 0 value is the proper indication of the end of file for read() and sysread().

63. How do I sort a hash by the hash value?
Here’s a program that prints the contents of the grades hash, sorted numerically by the hash value:
#!/usr/bin/perl –w
# Help sort a hash by the hash ‘value’, not the ‘key’. To highest).
# sub hashValueAscendingNum { $grades{$a} $grades{$b}; }
# Help sort a hash by the hash ‘value’, not the ‘key’.
# Values are returned in descending numeric order
# (highest to lowest).
sub hashValueDescendingNum {
$grades{$b} $grades{$a};
}
%grades = ( student1 => 90, student2 => 75, student3 => 96, student4 => 55, student5 => 76 );
print “ntGRADES IN ASCENDING NUMERIC ORDER:n”;
foreach $key (sort hashValueAscendingNum (keys(%grades))) {
print “tt$grades{$key} tt $keyn”;
}
print “ntGRADES IN DESCENDING NUMERIC ORDER:n”;
foreach $key (sort hashValueDescendingNum (keys(%grades))) {
print “tt$grades{$key} tt $keyn”;
}

64. How do find the length of an array?
scalar @array

65. 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.

66. 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.

67. 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.

68. 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.

69. How do I do for each element in an array?
#!/usr/bin/perl –w
@homeRunHitters = (‘McGwire’, ‘Sosa’, ‘Maris’, ‘Ruth’);
Foreach (@homeRunHitters) {
print “$_ hit a lot of home runs in one yearn”;
}

70. How do I replace every character in a file with a comma?
perl -pi.bak -e ‘s/t/,/g’ myfile.txt

71. What is the easiest way to download the contents of a URL with Perl?
Once you have the libwww-perl library, LWP.pm installed, the code is this:
#!/usr/bin/perl
use LWP::Simple;
$url = get ‘http://www.websitename.com/’;

72. How to concatenate strings in Perl?
Through . operator.

73. 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”;
}

74. Assume that $ref refers to a scalar, an array, a hash or to some nested data structure.
Explain the following statements:
$$ref;                        # returns a scalar
$$ref[0];                          # returns the first element of that array
$ref- > [0];                       # returns the first element of that array
@$ref;                             # returns the contents of that array, or number of elements, in scalar context
$&$ref;                            # returns the last index in that array
$ref- > [0][5];                  # returns the sixth element in the first row
@{$ref- > {key}}            # returns the contents of the array that is the value of the key “key”

75. Perl uses single or double quotes to surround a zero or more characters. Are the single(‘ ‘) or double quotes (” “) identical?
They are not identical. There are several differences between using single quotes and double quotes for strings.
1. The double-quoted string will perform variable interpolation on its contents. That is, any variable references inside the quotes will be replaced by the actual values.
2. The single-quoted string will print just like it is. It doesn’t care the dollar signs.
3. The double-quoted string can contain the escape characters like newline, tab, carraige return, etc.
4. The single-quoted string can contain the escape sequences, like single quote, backward slash, etc.

76. 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)

77. How do you give functions private variables that retain their values between calls?
Create a scope surrounding that sub that contains lexicals. Only lexical variables are truly private, and they will persist even when their block exits if something still cares about them. Thus: { my $i = 0; sub next_i { $i++ } sub last_i { –$i } } creates two functions that share a private variable. The $i variable will not be deallocated when its block goes away because next_i and last_i need to be able to access it.

78. Explain the difference between the following in Perl: $array[3] vs. $array->[3]
Because Perl’s basic data structure is all flat, references are the only way to build complex structures, which means references can be used in very tricky ways. This question is easy, though. In $array[3], “array” is the (symbolic) name of an array (@array) and $array[3] refers to the 4th element of this named array. In $array->[3], “array” is a hard reference to a (possibly anonymous) array, i.e., $array is the reference to
this array, so $array->[3] is the 4th element of this array being referenced.

79. How to remove duplicates from an array?
There is one simple and elegant solution for removing duplicates from a list in PERL
@array = (2,4,3,3,4,6,2);
my %seen = ();
my @unique = grep { ! $seen{ $_ }++ }
@array;
print “@unique”;

PERL Questions and Answers pdf Download