Perl for EDA
Perl is a high-level programming language.
Larry Wall invented Perl and thousands have contributed their time making it a
very powerful tool. Perl borrows heavily from the C programming language and
copies the really useful bits from sed, awk, Unix shell, and many other tools
and languages.
Perl is a script language, which is compiled each time before running
Perl's process, file, and text manipulation facilities make it particularly well-suited for tasks involving automatic code generation, report filtering, netlist patching, generating test vectors and controlling tools.
Perl is FREE so maybe you should use it
too.
These pages offer advice and examples for
improving design productivity through with Perl.
Comments and Commands
After the header line: #!/usr/bin/perl
there are either empty lines with no effect or command lines or commentary
lines. Everything from and behind a "#" up to the end of the
line is comment and has no effect on the program. Commands start with the first
non space charachter on a line and end with a ";". So one can
continue a command over several lines and terminates it only with the
semicolon.
Direct commands and subroutines
Normal commands are executed
in the order written in the script. But subroutines can be placed anywhere and
will only be evaluated when called from a normal command line. Perl knows it's
a subroutine if it the code is preceded with a "sub" and enclosed in
a block like: sub name { command;}
Other special lines
Perl can include other
programming code with: require something or with use something.
Quotations
Single quote: '' or: q//
Double quote: "" or: qq//
Quote for execution: `` or: qx//
Quote a list of words: ('term1','term2','term3') or: qw/term1 term2
term3/
Quote a quoted string: qq/"$name" is $name/;
Quote something wich contains "/": qq!/usr/bin/$file is readdy!;
Scalar and list context
That perl distinguishes
between scalar and list context is the big feature, which makes it unique and
more useful then most other script languages.
A subroutine can return lists and not only scalars like in C. Or an array gives
the number of elements in a scalar context and the elements itself in a list
context.
The enormous value of that feature should be evident.
Variables and
Operators
General
There are scalar variables,
one and two dimensional arrays and associative arrays. Instead of declaring a
variable, one precedes it with a special character. $variable is a
normal scalar variable. @variable is an array and %variable is an
associative array. The user of perl does not have to distinguish between a
number and a string in a variable. Perl switches the type if necessary.
Scalars
Fill in a scalar with: $price
= 300; $name = "JOHN"; Calculate with it like: $price *= 2;
$price = $oldprice * 4; $count++; $worth--; Print out the value of a scalar
with: print $price,"\n";
Arrays
Fill in a value: $arr[0] =
"Fred"; $arr[1] = "John"; Print out this array: print
join(' ',@arr),"\n";
If two dimensional: $arr[0][0] = 5; $arr[0][1] = 7;
Hashes (Associative Arrays)
Fill in a single element
with: $hash{'fred'} = "USA"; $hash{'john'} = "CANADA";
Fill in the entire hash:
%a = (
'r1', 'this is val of r1',
'r2', 'this is val of r2',
'r3', 'this is val of r3',
);
or with:
%a = (
r1 => 'this is val of r1',
r2 => 'this is val of r2',
r3 => 'this is val of r3',
);
Assignments
Put something into a variable
with a "=" or with some combined operator which assigns and
does something at the same time:
$var = "string"; Puts the string into $var
$var = 5; Puts a number into $var
$var .= "string"; Appends string to $var
$var += 5; Adds number to $var
$var *= 5; Multipliy with 5
$var ||= 5; If $var is 0 make it 5
$var x= 3; Make $var to three times $var as string: from a to aaa
Modify and assign with:
($new = $old) =~ s/pattern/replacement/;
Comparisons
Compare strings with: eq
ne like in: $name eq "mary".
Compare numbers with: == != >= <= <=> like in: $price ==
400.
And/Or/Not
Acct on success or failure of
an expression: $yes or die; means exit if $yes is not set.
For AND we have: && and "and" and for OR we
have: || or "or". Not is "!" or "not".
AND,OR and NOT are regularly used in if() statements:
if($first && $second){....;}
if($first || $second){....;}
if($first && ! $second{....;} means that $first must be non zero
but $second must not be so.
But many NOT's can be handled more reasonable with the unless() statement.
Instead:
print if ! $noway; one uses: print unless $noway;
Branching
if
if(condition){
command;
}elsif(condition){
command;
}else{
command;
}
command if condition;
unless (just the opposite of if)
unless(condition){
command;
}else{
command;
}
command unless condition;
Looping
while
while(condition){
command;
}
# Go prematurely to the next iteration
while(condition){
command;
next if condition;
command;
}
# Prematureley abort the loop with last
while(condition){
command;
last if condition;
}
# Prematurely continue the loop but do continue{} in any case
while(condition){
command;
continue if condition;
command;
}continue{
command;
}
# Redo the loop without evaluating while(condtion)
while(condtion){
command;
redo if condition;
}
command while condition;
until (just the opposite of while)
until(condition){
command;
}
until(condition){
command;
next if condition;
command;
}
until(condition){
command;
last if condition;
}
until(condition){
command;
continue if condition;
command;
}continue{
command;
}
command until condtion;
for (=foreach)
# Iterate over @data and have each value in $_
for(@data){
print $_,"\n";
}
# Get each value into $info iteratively
for $info (@data){
print $info,"\n";
}
# Iterate over a range of numbers
for $num (1..100){
next if $num % 2;
print $num,"\n";
}
# Eternal loop with (;;)
for (;;){
$num++;
last if $num > 100;
}
map
# syntax
map (command,list);
map {comm1;comm2;comm3;} list;
# example
map (rename($_,lc($_),<*>);
File Test Operators
File test operators check for
the status of a file: Some examples:
-f $file |
It's a plain file |
-d $file |
It's a directory |
-r $file |
Readable file |
-x $file |
Executable file |
-w $file |
Writable file |
-o $file |
We are owner |
-l $file |
File is a link |
-e $file |
File exists |
-z $file |
File has zero size, but
exists |
-s $file |
File is greater than zero |
-t FILEHANDLE |
This filehandle is connected
to a tty |
-T $file |
Text file |
-B $file |
Binary file |
-M $file |
Returns the day number of
last modification time |
Regular Expressions
What it is
A regular expression is an
abstract formulation of a string. Usually one has a search pattern and a match
which is the found string. There is also a replacement for the match, if a
substitution is made.
Patterns
A pattern stands for either one,
any number, several, a particular number or none cases of a character or a character-set
given literally, abstractly or octaly.
PATTERN |
MATCH |
. |
any character (dot) |
.* |
any number on any character
(dot asterix) |
a* |
the maximum of consecutive
a's |
a*? |
the minimum of consecutive
a's |
.? |
one or none of any
characters |
.+ |
one or more of any
character |
.{3,7} |
three up to seven of any
characters, but as many as possible |
.{3,7}? |
three up to seven, but the
fewest number possible |
.{3,} |
at least 3 of any character
|
.{3} |
exactly 3 times any
character |
[ab] |
a or b |
[^ab] |
not a and also not b |
[a-z] |
any of a through z |
^a |
a at beginning of string |
a$ |
a at end of string |
A|bb|CCC |
A or bb or CCC |
tele(f|ph)one |
telefone or telephone |
\w |
A-Z or a-z or _ |
\W |
none of the above |
\d |
0-9 |
\D |
none of 0-9 |
\s |
space or \t or \n (white
space) |
\S |
non space |
\t |
tabulator |
\n |
newline |
\r |
carridge return |
\b |
word boundary |
\bkey |
matches key but not
housekey |
(?#.......) |
Comment |
(?i) |
Case insensitive match.
This can be inside a pattern variable. |
(?:a|b|c) |
a or b or c, but without
string in $n |
(?=.....) |
Match ..... but do not
store in $& |
(?!.....) |
Anything but ..... and do
not store in $& |
Substitutions
One can replace found matches
with a replacement with the s/pattern/replacement/; statement.
The "s" is the command. Then there follow three delimiters with first
a search pattern and second a replacement between them. If there are
"/" within the pattern or the replacement then one chooses another
delimiter than "/" for instance a "!".
To change the content of a variable do: $var =~ s/pattern/replacement/;
To put the changed value into another variable, without distorting the original
variable do:
($name = $line) =~ s/^(\w+).*$/$1/;
COMMAND |
WHAT it DOES |
|
s/A/B/; |
substitute the first a in a
string with B |
|
s/A/B/g; |
substitute every a with a B
|
|
s/A+/A/g; |
substitute any number of a
with one A |
|
s/^#//; |
substitute a leading # with
nothing. i.e remove it |
|
s/^/#/; |
prepend a # to the string |
|
s/A(\d+)/B$1/g; |
substitute a followed by a
number with b followed by the same number |
|
s/(\d+)/$1*3/e; |
substitute the found number
with 3 times it's value |
|
Use two "e" for
to get an eval effect: |
|
|
perl -e '$aa = 4; $bb =
'$aa'; $bb =~ s/(\$\w+)/$1/ee; print $bb,"\n";' |
|
|
s/here goes
date/$date/g; |
substitute "here goes
date" with the value of $date |
|
s/(Masumi) (Nakatomi)/$2
$1/g; |
switch the two terms |
|
s/\000//g; |
remove null charachters |
|
s/$/\033/; |
append a ^M to make it
readable for dos |
|
Input and Output
Output a value from a variable
print
$var,"\n";
Output a formated string
printf("%-20s%10d",$user,$wage);
Read in a value into a variable and remove
the newline
chomp() (perl5) removes a
newline if one is there. The chop() (perl4) removes any last character.
chomp($var = <STDIN>);
Read in a file an process its linewise
open(IN,"<filename") || die "Cannot open filename for input\n";
while(<IN>){
command;
}
close IN;
Read a file into an array
open(AAA,"<infile") || die "Cannot open infile\n";
@bigarray = <AAA>;
close AAA;
Output into a file
open(OUT,">file") || die "Cannot oben file for output\n";
while(condition){
print OUT $mystuff;
}
close OUT;
Check, whether open file would yield
something (eof)
open(IN,"<file") || die "Cannot open file\n";
if(eof(IN)){
print "File is empty\n";
}else{
while(<IN>){
print;
}
}
close IN;
Process Files
mentioned on the Commandline
The empty filehandle
"<>" reads in each file iteratively. The name of the current
processed file is in $ARGV. For example print each line of several files
prepended with its filename:
while(<>){
$file = $ARGV;
print $file,"\t",$_;
open(IN,"<$file") or warn "Cannot open $file\n";
....commands for this file....
close(IN);
}
Get Filenames
Get current directory at once
@dir = <*>;
Use current directory iteratively
while(<*>){
...commands...
}
Select files with <>
@files = </longpath/*.c>;
Select files with glob()
This is the official way of
globbing:
@files = glob("$mypatch/*$suffix");
Readdir()
Perl can also read a
directory itself, without a globing shell. This is faster and more
controllable, but one has to use opendir() and closedir().
opendir(DIR,".") or die "Cannot open dir.\n";
while(readdir DIR){
rename $_,lc($_);
}
closedir(DIR);
Pipe Input and
Output from/to Unix Commands
Process Data from a Unix Pipe
open(IN,"unixcommand|") || die "Could not execute unixcommand\n";
while(<IN>){
command;
}
close IN;
Output Data into a Unix Pipe
open(OUT,"|more") || die "Could not open the pipe to more\n";
for $name (@names){
$length = length($name);
print OUT "The name $name consists of $lenght characters\n";
}
close OUT;
Execute Unix
Commands
Execute a Unix Command and forget about the
Output
system("someprog -auexe
-fv $filename");
Execute a Unix Command an store the Output
into a Variable
If it's just one line or a
string:
chomp($date = qx!/usr/bin/date!); The chomp() (perl5) removes the trailing
"\n". $date gets the date.
If it gives a series of lines one put's the output into an array:
chomp(@alllines = qx!/usr/bin/who!);
Replace the whole perl program by a unix
program
exec anotherprog; But then the perl program is gone.
The Perl built-in
Functions
String Functions
Get all upper case
with: |
$name = uc($name); |
Get only first letter
uppercase: |
$name = ucfirst($name); |
Get all lowercase: |
$name = lc($name); |
Get only first letter
lowercase: |
$name = lcfirst($name); |
Get the length of a string:
|
$size = length($string); |
Extract 5-th to 10-th
characters from a string: |
$part =
substr($whole,4,5); |
Remove line ending: |
chomp($var); |
Remove last character: |
chop($var); |
Crypt a string: |
$code =
crypt($word,$salt); |
Execute a string as perl
code: |
eval $var; |
Show position of substring
in string: |
$pos =
index($string,$substring); |
Show position of last
substring in string: |
$pos =
rindex($string,$substring); |
Quote all metacharachters: |
$quote =
quotemeta($string); |
Array Functions
Get expressions for which a
command returned true: |
@found =
grep(/[Jj]ohn/,@users); |
Applay a command to each
element of an array: |
@new =
map(lc($_),@start); |
Put all array elements into
a single string: |
$string = join('
',@arr); |
Split a string and make an
array out of it: |
@data =
split(/&/,$ENV{'QUERY_STRING'};
|
Sort an array: |
sort(@salery); |
Reverse an array: |
reverse(@salery); |
Get the keys of a
hash(associative array): |
keys(%hash); |
Get the values of a hash: |
values(%hash); |
Get key and value of a hash
iteratively: |
each(%hash); |
Delete an array: |
@arr = (); |
Delete an element of a
hash: |
delete $hash{$key}; |
Check for a hash key: |
if(exists
$hash{$key}){;} |
Check wether a hash has
elements: |
scalar %hash; |
Cut of last element of an
array and return it: |
$last = pop(@IQ_list); |
Cut of first element of an
array and return it: |
$first = shift(@topguy); |
Append an array element at
the end: |
push(@waiting,$name); |
Prepend an array element to
the front: |
unshift(@nowait,$name); |
Remove first 2 chars an
replace them with $var: |
splice(@arr,0,2,$var); |
Get the number of elements
of an array: |
scalar @arr; |
Get the last index of an
array: |
$lastindex = $#arr; |
File Functions
Open a file for input: |
open(IN,"</path/file")
|| die "Cannot open file\n";
|
Open a file for output: |
open(OUT,">/path/file")
|| die "Cannot open file\n";
|
Open for appending: |
open(OUT,">>$file")
|| &myerr("Couldn't open $file"); |
Close a file: |
close OUT; |
Set permissions: |
chmod 0755, $file; |
Delete a file: |
unlink $file; |
Rename a file: |
rename $file, $newname; |
Make a hard link: |
link $existing_file,
$link_name; |
Make a symbolic link:
|
symlink $existing_file,
$link_name; |
Make a directory: |
mkdir $dirname, 0755; |
Delete a directory: |
rmdir $dirname; |
Reduce a file's size: |
truncate $file, $size; |
Change owner- and group-ID:
|
chown $uid, $gid; |
Find the real file of a
symlink: |
$file = readlink
$linkfile; |
Get all the file infos: |
@stat = stat $file; |
|
|
Conversions Functions
Number to character: |
chr $num; |
Charachter to number: |
ord($char); |
Hex to decimal: |
hex(0x4F); |
Octal to decimal: |
oct(0700); |
Get localtime from time: |
localtime(time); |
Get greenwich meantime: |
gmtime(time); |
Pack variables into string:
|
$string =
pack("C4",split(/\./,$IP));
|
Unpack the above string: |
@arr =
unpack("C4",$string); |
Subroutines
(=functions in C++)
Define a Subroutine
sub mysub {
command;
}
Example:
sub myerr {
print "The following error occured:\n";
print $_[0],"\n";
&cleanup;
exit(1);
}
Call a Subroutine
&mysub;
Give Arguments to a Subroutine
&mysub(@data);
Receive Arguments in the Subroutine
As global variables:
sub mysub {
@myarr = @_;
}
sub mysub {
($dat1,$dat2,$dat3) = @_;
}
As local variables:
sub mysub {
local($dat1,$dat2,$dat3) = @_;
}
Some of the Special
Variables
SYNTAX
|
MEANING
|
$_ |
String from current loop.
e.g. for(@arr){ $field = $_ . " ok"; } |
$. |
Line number from current
file processed with: while(<XX>){ |
$0 |
Program name |
$$ |
Process id of current
program |
$< |
The real uid of current
program |
$> |
Effective uid of current
program |
$| |
For flushing output: select
XXX; $| = 1; |
$& |
The match of the last pattern
search |
$1.... |
The ()-embraced matches of
the last pattern search |
$` |
The string to the left of
the last match |
$' |
The string to the right of
the last match |
Forking
Forking is very easy! Just
fork. One puts the fork in a three way if(){} to separately the parent, the
child and the error.
if($pid = fork){
# Parent
command;
}elsif($pid == 0){
# Child
command;
# The child must end with an exit!!
exit;
}else{
# Error
die "Fork did not work\n";
}
Building Pipes for
forked Children
Building a Pipe
pipe(READHANDLE,WRITEHANDLE);
Flushing the Pipe
select(WRITEHANDLE); $| = 1; select(STDOUT);
Setting up two Pipes between the Parent and
a Child
pipe(FROMCHILD,TOCHILD); select(TOCHILD); $| = 1; select(STDOUT);
pipe(FROMPARENT,TOPARENT);select(TOPARENT);$| = 1; select(STDOUT);
if($pid = fork){
# Parent
close FROMPARENT;
close TOPARENT;
command;
}elsif($pid == 0){
# Child
close FROMCHILD;
close TOCHILD;
command;
exit;
}else{
# Error
command;
exit;
}
Building a Socket
Connection to another Computer
# Somwhere at the beginning of the script
require 5.002;
use Socket;
use sigtrap;
# Prepare infos
$port = 80;
$remote = 'remotehost.domain';
$iaddr = inet_aton($remote);
$paddr = sockaddr_in($port,$iaddr);
# Socket
socket(S,AF_INET,SOCK_STREAM,$proto) or die $!;
# Flush socket
select(S); $| = 1; select(STDOUT);
# Connect
connect(S,$paddr) or die $!;
# Print to socket
print S "something\n";
# Read from socket
$gotit = <S>;
# Or read a single character only
read(S,$char,1);
# Close the socket
close(S);
Get Unix User and
Network Information
Get the password entry for a
particular user with: @entry = getpwnam("$user");
Or with bye user ID: @entry = getpwuid("$UID");
One can information for group, host, network, services, protocols in the above
way with the commands: getgrnam, getgrid, gethostbyname, gethostbyaddr,
getnetbyname, getnetbyaddr, getservbyname, getservbyport, getprotobyname,
getprotobynumber.
If one wants to get all the entries of a particular category one can loop
through them by:
setpwent;
while(@he = getpwent){
commands...
}
entpwent;
For example: Get a list of all users with their home directories:
setpwent;
while(@he = getpwent){
printf("%-20s%-30s\n",$he[0],$he[7]);
}
endpwent;
The same principle works for
all the above data categories. But most of them need a "stayopen"
behind the set command.
Arithmetics
Addition: +
Subtraction: -
Multiplication: *
Division: /
Rise to the power of: **
Rise e to the pwoer of: exp()
Modulus: %
Square root: sqrt()
Absolut value: abs()
Tangens: atan2()
Sinus: sin()
Cosine: cos()
Random number: rand()
Formatting Output with
"format"
This should be simplification
of the printf formatting. One formats once only and then it will be used for
every write to a specified file handle. Prepare a format somwhere in the program:
format filehandle =
@<<<<<<<<<<@###.#####@>>>>>>>>>>@||||||||||
$var1, $var3, $var4
.
Now use write to print into that
filhandle according to the format:
write FILEHANDLE;
The @<<< does left adjustment, the @>>> right adjustment, @##.##
is for numericals and @||| centers.
Command line
Switches
Show the version number of
perl: |
perl -v; |
Check a new program without
runing it: |
perl -wc <file>; |
Have an editing command on
the command line: |
perl -e 'command'; |
Automatically print while
precessing lines: |
perl -pe 'command'
<file>; |
Remove line endings and add
them again: |
perl -lpe 'command'
<file>; |
Edit a file in place: |
perl -i -pe 'command'
<file>; |
Autosplit the lines while editing:
|
perl -a -e 'print if
$F[3] =~ /ETH/;' <file>; |
Have an input loop without
printing: |
perl -ne 'command'
<file>; |
1. How do you know the reference of a variable whether it is a
reference,scaller, hash or array?
Ans: there is a 'ref' function that lets you know
-----------------------------------------------------------------
2. what is the difference between 'use' and 'require' function?
Ans: 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 extentsion. Require: 1. The method is used for both libraries
( package ) and modules 2. The include objects are varified 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'?
Ans. 'chop' functiononly removes the last character completely 'from the
scaler, 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
Ans> @solution = sort {lc $a comp lc$b } @arr.
------------------------------------------------------------------
5. What is '->' in Perl?
Ans. it is a symbolic link to link one file name to a new name. so lets 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?
Ans. 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
if (! -s "$temp/engl_2/wf"){ System "mkdir -p $temp/engl_2/wf";
} if (! -s "$temp/backup_basedir"){ system "mkdir -p
$temp/backup_basedir"; } ${pack_2} = -M
"${temp}/engl_2/wf/${wf_package_name}.data"; ${new_pack}= -M
"{pack}/package.data"; 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?
-----------------------------------------------------------------------
8. How to substitute a particular string in a file containing million of
record?
Ans. perl -p -ibak -e 's/search_str/replace_str/g' filename
-----------------------------------------------------------------------
9. 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?
Ans. use XYZ my $objref =XYZ -> new() OR, bless $objref, 'XYZ';
---------------------------------------------------------------
10. what is meant by a 'pack' in perl?
Ans. 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 contaings a con-catenation of the converted values. Typically, each
converted values looks like its machine-level repesentation. for example, on
32-bit machines a converted integer may be representated by a sequence of 4
bytes.
---------------------------------------------------------------------------------------------------
11. how to implement stack in Perl?
Ans. through push() and shift() function. push adds the element at the last of
array and shift() removes from the beginning of an array.
---------------------------------------------------------------------------------------------------
12. What is Grep used for in Perl?
Ans. Grep is used with regular expression to check if a parituclar value exist
in an array. it returns 0 it the value does not exists, 1 otherwise.
--------------------------------------------------------------------------------------------------
13. How to code in Perl to implement the tail function in unix?
And. You have to maintain a structure to store the line number and the size of
the file at that time eg. 1-10bytes, 2-18bytes.. 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 thens
tart reading till the end. ---------------------------------------------------------------------------------------------------
14. Explain the difference between 'my' and 'local' variable scope
declarations?
Ans. 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 fucntions called within that block, but one defined as 'local'
canlive within the block and have its visibility in the functions called within
that block. ------------------------------------------------------------------------------------------------------
15. How do you navigate thorugh an XML documents?
Ans. You can use the XML::DOM navigation methods to navigate thorugh an
XML::DOM node tree and use the getnodevalue to recover the data. DOM Parser is
used when it is neede to do node operation. Instead we may use SAX parser if
you require simple processing of the xml structure.
-------------------------------------------------------------------------------------------------------
16. How to delete an entire directory containing few files in the directory?
Ans. 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); -----------------------------------------------------------------------------------------------------------
17. What are the arguements we normally use for Perl Interpreter
Ans. -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)
------------------------------------------------------------------------------------------------------------
18. what is it meants by '$_'?
Ans. it is a default variable which holds automatically, a list of arguements
passed to the subroutine within parentheses.
-------------------------------------------------------------------------------------------------------------
19. How to connect to sql server through Perl?
Ans. 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
$dh=DBI->connect("dbi:mysql")
---------------------------------------------------------------------------------------
20. What is the purpose of -w,strict and -T?
Ans. -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.
----------------------------------------------------------------------------------------
21. What is the difference between die and exit?
Ans. 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.
-----------------------------------------------------------------------------------------
22. where do you go for perl help?
Ans. perldoc command with -f option is the best. i also go to search.cpan.org
for help.
----------------------------------------------------------------------------------------
23. what is the Tk module?
Ans. it provides a GUI interface
----------------------------------------------------------------------------------------
24. what is your favorite module in Perl?
Ans. CGI and DBI. CGI(Common Gateway Interface) because we do not need to worry
about the subtle features of form processing.
-----------------------------------------------------------------------------------------
25. What is hash in perl?
Ans. 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 scallars and called as keys. Each key corresponds to some value. Hashes are
represented by % followed by some name.
-------------------------------------------------------------------------------------------
26.what does 'qw()' mean? what's the use of it?
Ans. qw is a construct which quotes words delimited by spaces. use it when you
have long list of words that are nto quoted or youjust do not want to type
those quotes as youtype out a list of space delimited words. like @a = qw(1234)
which is like @a=("1","2","3","4"); -------------------------------------------------------------------------------------------
27. what is the difference between Perl and shell script?
Ans. whatever you can do in shell script can be done in Perl.however 1. Perl
gives you an extended advantages of having enormous library. 2. you do not need
to write everything from scartch.
-------------------------------------------------------------------------------------------
28. what is stderr() in perl?
Ans. special file handler to standard error in any package.
--------------------------------------------------------------------------------------------
29. what is a regular expression?
Ans. it defines a pattern for a search to match.
--------------------------------------------------------------------------------------------
30. what is the difference between for and foreach?
Ans. functionally, there is no difference between them.
------------------------------------------------------------------------------------------------
31, what is the difference between exec and system?
Ans. 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.
------------------------------------------------------------------------------------------------
32. What is CPAN?
Ans. CPAN is comprehensive Perl Archive Network. its a repository contains
thousands of Perl Modules, source and documentation, and all under GNU/GPL or
smilar licence. you can go to www.cpan.org for more details. Some linux
distribution provide a till names 'cpan; which you can install packages
directly from cpan.
------------------------------------------------------------------------------------------------
33. what does this symbol mean '->'?
Ans. In Perl it is an infix dereference operator. for array subscript, or a
hash key, or a subroutine, then the ihs must be a reference. can also be used
as method invocation.
------------------------------------------------------------------------------------------------
34. what is a DataHash()
Ans. in Win32::ODBC, DataHash() function is used to get the data fetched
thorugh the sql statement in a hash format.
-------------------------------------------------------------------------------------------------
35. what is the difference between C and Perl?
Ans. make up
--------------------------------------------------------------------------------------------------
36. Perl regular exp are greedy. what is it mean by that?
Ans. it tries to match the longest string possible. -------------------------------------------------------------------------------------------------
37. what does the world '&my variable' mean?
Ans. &myvariable is calling a sub-routine. & is used to indentify a
subroutine. ----------------------------------------------------------------------------------------------------
38, what is it meant by @ISA, @EXPORT, @EXPORT_0?
Ans @ISA -> each package has its own @ISA array. this array keep track of
classes it is inheriting. ex: package child; @ISA=( parentclass); @EXPORT this
array stores the subroutins to be exported from a module. @EXPORT_OK this array
stores the subroutins to be exported only on request.
--------------------------------------------------------------------------------------------------------
39.what package you use to create a windows services?
ans. use Win32::OLE.
--------------------------------------------------------------------------------------------------------
40, How to start Perl in interactive mode?
Ans. perl -e -d 1 PerlConsole. ---------------------------------------------------------------------------------------------------------
41. How do I set environment variables in Perl programs?
Ans. 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/yourname/bin';
--------------------------------------------------------------------------------------------------------------
42. what is the difference between C++ and Perl?
Ans. 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.
---------------------------------------------------------------------------------------------------------------
43. How to open and read data files with Perl?
Ans. 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);
------------------------------------------------------------------------------------------------------------------------
44. How do i do fill_in_the_blank for each file in a directory?
Ans. #!/usr/bin/perl -w opendir(DIR, "."); @files = readdir(DIR);
closedir(DIR); foreach $file (@files) { print "$file\n"; }
--------------------------------------------------------------------------------------------------------------------------
45. how do i generate a list of all .html files in a directory
Ans. 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 "$file\n"; }
-----------------------------------------------------------------------------------------------------
46. what is Perl one-liner?
Ans. 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.
-----------------------------------------------------------------------------------------------------
47, Assume both a local($var) and a my($var) exist, what's the difference
between ${var} and ${"var"}?
Ans. ${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.
-----------------------------------------------------------------------------------------------------
48. What happens when you return a reference to a private variable?
ans. Perl keeps track of your variables, whether dynamic or otherwise, and
doesn't free things before you're done using them
-----------------------------------------------------------------------------------------------------------
49. What are scalar data and scalar variables?
Ans. 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 aphanumeric
characters or underscores. It is case sensitive. --------------------------------------------------------------------------------------------------------------
50. Assuming $_ contains HTML, which of the following substitutions will remove
all tags in it?
Ans. You can't do that. If it weren't for HTML comments, improperly formatted
HTML, and tags with interesting data like < SCRIPT >, you could do this.
Alas, you cannot. It takes a lot more smarts, and quite frankly, a real parser.
--------------------------------------------------------------------------------------------------------------
51. I want users send data by formmail but when they send nothing or call it
from web site they will see error. codes in PHP like this: if
(isset($HTTP_POST_VARS)){ .......... } else{ echo ("error lalalalal")
} How it will look in perl?
Ans. In perl if ($ENV{'REQUEST_METHOD'} eq 'POST'){ ..... }
------------------------------------------------------------------------------------------------------------
52. What is the output of the following Perl program?
1 $p1 = "prog1.java"; 2 $p1 =~ s/(.*)\.java/$1.cpp/; 3 print
"$p1\n"; Ans. prog1.cpp
-----------------------------------------------------------------------------------------------------------
53. Why aren't Perl's patterns regular expressions?
Ans. Because Perl patterns have 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]+)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.
------------------------------------------------------------------------------------------------------------
54. What does Perl do if you try to exploit the execve(2) race involving setuid
scripts?
Ans. 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 < fill-in-the-blank > for each element in a hash?
Ans. 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"; }
-----------------------------------------------------------------------------------------
57. 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
"\n\tGRADES SORTED BY STUDENT NAME:\n"; foreach $key (sort
(keys(%grades))) { print "\t\t$key \t\t$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 }
---------------------------------------------------------------------------------------------------------
58. How do you print out the next line from a filehandle with all its bytes
reversed?
Ans. print scalar reverse scalar Surprisingly enough, you have to put both the
reverse and the into scalar context separately for this to work.
-------------------------------------------------------------------------------------------------------------
59. How do I send e-mail from a Perl/CGI program on a Unix system?
Ans. 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);
--------------------------------------------------------------------------------------------------------------
60. How to read from a pipeline with Perl?
Ans. 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);
----------------------------------------------------------------------------------------------------
61. 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].
------------------------------------------------------------------------------------------------------
62. What does `$result = f() .. g()' really return?
Ans. 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() );
---------------------------------------------------------------------
63. Why does Perl not have overloaded functions?
Ans. 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.
------------------------------------------------------------------------------------------------------
64. What does read() return at end of file?
Ans. 0 A defined (but false) 0 value is the proper indication of the end of
file for read() and sysread().
-------------------------------------------------------------------------------------------------------
65. What does `new $cur->{LINK}' do? (Assume the current package has no
new() function of its own.)
Ans. $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.
--------------------------------------------------------------------------------------------------------
66. How do I sort a hash by the hash value?
Ans. 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 "\n\tGRADES IN ASCENDING NUMERIC
ORDER:\n"; foreach $key (sort hashValueAscendingNum (keys(%grades))) {
print "\t\t$grades{$key} \t\t $key\n"; } print "\n\tGRADES IN
DESCENDING NUMERIC ORDER:\n"; foreach $key (sort hashValueDescendingNum
(keys(%grades))) { print "\t\t$grades{$key} \t\t $key\n"; }
---------------------------------------------------------------------------------------------------------
67. How to read file into hash array ?
Ans. open(IN, ") { chomp; $hash_table{$_} = 0; } close IN; print "$_
= $hash_table{$_}\n" foreach keys %hash_table;
-----------------------------------------------------------------------------------------------------------
68. how do find the length of an array?
Ans. $@array
------------------------------------------------------------------------------------------------------------
69, What value is returned by a lone `return;' statement?
Ans. 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.
------------------------------------------------------------------------------------------------------------
70. What's the difference between /^Foo/s and /^Foo/?
Ans. 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.
--------------------------------------------------------------------------------------------------------------
71. Does Perl have reference type?
Ans. 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. ---------------------------------------------------------------------------------------------
72. How to dereference a reference?
Ans. 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.
----------------------------------------------------------------------------------------------
73. What does length(%HASH) produce if you have thirty-seven random keys in a
newly created hash?
Ans.5 length() is a built-in prototyped as sub length($), and a scalar
prototype silently changes aggregates into radically different forms. The
scalar sense of a hash is false (0) if it's empty, otherwise it's a string
representing the fullness of the buckets, like "18/32" or
"39/64". The length of that string is likely to be 5. Likewise,
`length(@a)' would be 2 if there were 37 elements in @a.
------------------------------------------------------------------------------------------------
74. If EXPR is an arbitrary expression, what is the difference between
$Foo::{EXPR} and *{"Foo::".EXPR}?
Ans. The second is disallowed under `use strict "refs"'.
Dereferencing a string with *{"STR"} is disallowed under the refs
stricture, although *{STR} would not be. This is similar in spirit to the way
${"STR"} is always the symbol table variable, while ${STR} may be the
lexical variable. If it's not a bareword, you're playing with the symbol table
in a particular dynamic fashion. ----------------------------------------------------------------------------------------------------
75. How do I do < fill-in-the-blank > for each element in an array?
Ans. #!/usr/bin/perl -w @homeRunHitters = ('McGwire', 'Sosa', 'Maris', 'Ruth');
foreach (@homeRunHitters) { print "$_ hit a lot of home runs in one
year\n"; }
-------------------------------------------------------------------------------------------------------
76. How do I replace every character in a file with a comma?
Ans. perl -pi.bak -e 's/\t/,/g' myfile.txt
--------------------------------------------------------------------------------------------------------
77. What is the easiest way to download the contents of a URL with Perl?
Ans. 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/';
---------------------------------------------------------------------------------------------------------
78. how to concatinate strings in Perl?
Ans. through . operator.
----------------------------------------------------------------------------------------------------------
79. How do I read command-line arguments with Perl?
Ans. 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"; }
--------------------------------------------------------------------------------------------------------------------
80. When would `local $_' in a function ruin your day?
Ans. When your caller was in the middle for a while(m//g) loop The /g state on
a global variable is not protected by running local on it. That'll teach you to
stop using locals. Too bad $_ can't be the target of a my() -- yet.
-----------------------------------------------------------------------------------------------------------------------
81. What happens to objects lost in "unreachable" memory..... ?
Ans. What happens to objects lost in "unreachable" memory, such as
the object returned by Ob->new() in `{ my $ap; $ap = [ Ob->new(), \$ap ];
}' ? Their destructors are called when that interpreter thread shuts down. When
the interpreter exits, it first does an exhaustive search looking for anything
that it allocated. This allows Perl to be used in embedded and multithreaded
applications safely, and furthermore guarantees correctness of object code.
-------------------------------------------------------------------------------------------------------------------------
82. Assume that $ref refers to a scalar, an array, a hash or to some nested
data structure. Explain the following statements:
Ans. $$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"
------------------------------------------------------------------------------------------------------
83. How do you match one letter in the current locale?
Ans. /[^\W_\d]/ We don't have full POSIX regexps, so you can't get at the
isalpha() macro save indirectly. You ask for one byte which is neither a
non-alphanumunder, nor an under, nor a numeric. That leaves just the alphas,
which is what you want.
-------------------------------------------------------------------------------------------------------------
84. How do I print the entire contents of an array with Perl?
Ans. To answer this question, we first need a sample array. Let's assume that
you have an array that contains the name of baseball teams, like this: @teams =
('cubs', 'reds', 'yankees', 'dodgers'); If you just want to print the array
with the array members separated by blank spaces, you can just print the array
like this: @teams = ('cubs', 'reds', 'yankees', 'dodgers'); print
"@teams\n"; But that's not usually the case. More often, you want
each element printed on a separate line. To achieve this, you can use this
code: @teams = ('cubs', 'reds', 'yankees', 'dodgers'); foreach (@teams) { print
"$_\n"; } ------------------------------------------------------------------------------------------------------------------
84. Perl uses single or double quotes to surround a zero or more characters.
Are the single(' ') or double quotes (" ") identical?
Ans. 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.
----------------------------------------------------------------------------------------------------------------------
85. How many ways can we express string in Perl?
Ans. 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)
------------------------------------------------------------------------------------------------------------
86. How do you give functions private variables that retain their values
between calls?
Ans. 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.
--------------------------------------------------------------------------------------------------------------
87. Explain the difference between the following in Perl: $array[3] vs.
$array->[3]
Ans. 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. ------------------------------------------------------------------------------------------------------
88, how to remove duplicates from an array?
Ans. 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";
Q1)
Compare Perl with C
S.No |
Perl |
C |
1 |
There
are several development tools in Perl as compare to C |
Development
tools are less and are not very advanced |
2 |
It
executes in a slower manner than C in a few situations |
C has
speed almost equal to that of Perl |
3 |
Code
can be hidden in Perl |
The
same is not possible in case of C |
4 |
Executable
can be created without depending on the additional tools |
Additional
tools is the prime requirement |
Q2) Can
you name the variables in which the chomp works? Also, how they are different
from one another?
These
are: Scalar and Array
Scalar
is generally denoted by symbol $ and it can have a variable which can either be
a strong or a number. An array on the other side is denoted by @ symbol. An
array is always a number. Both these variables have different namespace. The
scalar variables are capable to hold a value of 1 digit while array can have
more values. Both of them can be executed in the function whenever there is a
need of the same.
Q3) Is
it possible in the Perl to use code again and again? If so, which feature
enable user to that?
Yes, it
is possible in Perl. However, there is a limit on usage of the same code in the
same program. The users need not to worry about the complexity either as Perl
is equipped with a code trimming feature. It automatically guides users on how
to keep the code as short as possible. Code reusability is a prime example of
this. The feature that enables users to simply keep up the pace towards this is
“Inheritance”. The child class in this feature can use the methods of their
parent class.
Q4) How
can you represent the warning signs in the Perl in case of an error and what
are the options through which this task can be performed?
Ans: There is an option in Perl which is known
as WCommand Line. All the warning messages can be displayed using this and the
pragma function simply makes sure that the user can declare the variables
during appearance of warning messages. The entire program can be scrolled
easily and in fact, in a very short span of time using the in-built
debugger.
Q5)
While writing a program, why the code should be as short as possible?
Ans: Complex codes are not always easy to
handle. They are not even easy to be reused. Moreover, finding a bug in them is
not at all a difficult job. Any software or application if have complex or
lengthy code couldn’t work smoothly with the hardware and often have
compatibility issues. Generally, they take more time to operate and thus
becomes useless or of no preference for most of the users. The short code
always makes sure that the project can be made user-friendly and it enables
programmers to save a lot of time.
Q6) Can
you tell the meaning of the term debugging in the programming?
Ans: Well, every programmer is familiar with
this approach. The fact is there are many errors that declare their presence in
the programs due to reasons which are not always necessary to be known exactly.
Eliminating these errors is very essential for the smooth flow of the tasks.
Finding the bugs or the errors is known as debugging. The programming languages
can have in-built options for debugging or the programmers are free to consider
other options too.
Q7) What
are “Require” and “Use” statement in Perl and when it is used?
Ans: It is considered when it comes to
importing the functions in a way that they can be accessed directly during the
program. The users are free to get the results in case the sub statements are
not accurate. On the other side, the use statement is generally executed during
parsing.
Q8) In
Perl, is it possible for the programmers to prefer a dynamic approach when it
comes to loading the binary extension?
Ans: Yes, it is possible. The only need for
this is the system a programmer is using must support it. The other option is
to accomplish this task statically in case the system doesn’t allow the same.
Dynamic approach can help users to save time as they are free to perform some
basic tasks in their own way.
Q9) Name
a few arguments which are used in Perl frequently. Tell their meaning as well
Ans: These are as following
-d which
means debug
-w that indicates warning
-e means execute
-c which says non return compilation
Q10)
Tell something about the Associate Arrays in Perl and how they are significant
for the programmers?
Ans: It is basically one of the widely used
data type in the Perl after Scalar and Array. They are quite similar to that of
a hash table and there are a lot of functions which are quite similar to that
of the same.
Q11) Can
you add module file in Perl and what are the functions that simply enable you
to do so?
Ans: Yes, it is possible and there are
“Require” “Or” and “Use”
Q12)
What are the guidelines about the Perl Modules which a use should pay attention
to and follow?
Ans: There are various things that a user
should pay attention to. A few important ones are as follow:
1. The
user must always make it user that a Package Name should always begin with a
capital Letter
2. If there is a file name, the extension for the same could be .pm
3. The package should come from exporter class in case the object is not
considered for the same
Q13) For
executing a program in Perl, is there any basic condition which the users have
to fulfill?
Ans: The users must make sure that the program
they have accomplished should be passed through the interpreter before its
actual execution. It actually compiles the program in a reliable manner and the
best part is the users are free to ignore any spaces or marks in the
same.
Q14) How
can you say that Perl is compiler?
Ans: It is because the interpreter in the Perl
is actually free to convert simply the program into the small codes.
(OR)
Is Perl
a compiler or Interpreter?
The
programming language can also be used both as a compiler and as an interpreter.
It takes in the source codes and converts the same into bytecode that is
understandable by the programming language. You can then execute and run the
program. Therefore, the programming language can both be regarded as an
interpreter and a compiler.
Q15)
What does CPAN means?
Ans: It stands for Comprehensive Perl Archive
Network and is a large collection of all the documents and software related to
Perl. The programmers can access the same and can avoid the difficulties they
face. CPAN is of significance use for the programmers and they are free
to derive a lot of useful information from the same.
Q16)
While start working on a project, how you will decide Perl is suitable for the
same
Ans: The first thing to pay attention to is
whether the execution need is fast or not. If so, Perl is a good option to
consider. The users are free to keep up the pace with the flexibility as well.
Perl is highly flexible and it can enable users to keep up the pace with the
same. Perl is open source and is free from licenses issues. Perl has one of the
best and in fact largest free code repositories that simply make it one of the
best options to be considered. Also, it is one of the best programming
languages with a vast support available for the programmers.
Subscribe
to our youtube channel to get new updates..!
Q17) Name
the operators which are used in Perl and are common?
Ans: 1. Assignment Operators
2. Arithmetic Operators
3. Increment operators
4. Comparison operators
5. Logical Operators
6. String Operators
Q18)
Tell how can an array be made empty in Perl?
Ans: This can be done easily. For this, the
value of the array is set to zero and the users can then perform this task by
assigning the null list to it.
Related
Article: Overview Of Arrays
Q19)
Which among the Terms or Lists in Perl have maximum precedence and how you can
say that?
Ans: Terms have the maximum number of
precedence. It generally includes expressions, quotes and the same have word
precedence which is complex.
Q20)
What are the options with the help of which you can wrap scripts in the loops?
Ans: For this, there are
options –p and –n. The users are free to use this option as many
times as you can. There are no restrictions on the size of the scripts and
the loops.
Q21)
What is the significance of the warning messages in Perl and how they are
helpful to the users?
Ans: These are generally the messages that
simply let the user keep an eye on the quality of code. With the appropriate
messages, it becomes simple for a user to highlight problems. The user can set
the messages as optional while working on the programs.
Q22) How
the information can be inserted into the hashes in Perl?
Ans: There is no literal representation in the
content of a hash. The users have to make sure that the unwinding of the hash
before it is actually filled with the data. The value pairs can be created
simply and they can then be converted. In the process of conversion, the hashes
can be selected randomly.
(OR)
This
hash in this programming language is a group of key-values. These are scalar
values. The hashes are used after a % sign and can be created only by assigning
a value to it.
For
incorporating information in hashes, the key-value pairs should be created
which is known as the unwinding of hash. In this case, the even number items
are listed on the right called as values, and the ones stored on the left are
termed as keys.
Check
Out PERL Scripting Tutorials
Q23)
Tell one reason why Perl aliases are good enough to be considered and is faster
than references?
Ans: They don’t need dereferencing and that is
one of the best things about it. A lot of tasks that are not required or are
not usual can be avoided easily.
Q24)
Tell something about memory management in Perl?
Ans: When the programmers make use of a
variable in Perl, some memory get occupies. The users have to make sure that
the memory is utilized in the best possible manner. After a program is
executed, the files can be divided into the sections easily and can then be
managed.
Q25)
When you can make use of Perl Grep?
Ans: It is basically an important function in
Perl that simply let the programmers make sure that the elements that are considered
in Perl can be trusted for the long run. It enables programmers to get the
elements that are actually suitable with the criteria set by the users on the
functions.
Q26)
What is the significance of Chop functions in Perl and how the users can keep
up the pace with them?
Ans: Sometimes there is a need for the users
to avoid some random characters from the expression. The same is done in Perl
through the Chop Functions.
Q27) Can
the Compiled Form is stored as file in Perl?
PERL
Scripting Certification Training!
Ans: No it cannot be stored as a File
Q28)
Does Perl have Objects? What is the best thing about them you have come across?
Ans: Yes, Perl is equipped with some very
useful Objects. The best part is programmers are not forced to use them while
performing their task. The users can easily skip them in case they don’t felt
their need while writing the codes. There are certain Object Oriented modules
which are present in Perl and the users are free to consider them without
actually understanding the objects. However, it is recommended to the
programmers to go with the Objects in case the program is too complex.
Q29) How
Local Operator and My Operator are different from one another?
Ans: Both these are the methods that are
useful for assigning private values to a block. Local Operator only operates on
the Global Operator and it keeps the value of private operator. They can be
accessed at the end of the block. My Operator is considered for creating a new
variable. The variables created by it are always considered as private and
remains present in the block they are assigned.
(OR)
How to
get private values inside a subroutine or block?
The user
can use two ways to get private values in a subroutine. The ways are Local
operator or My operator.
1. Local
operator – This functions on global variable only. It takes in the private
variable and restores them at the end of any block arranged.
2. My operator – For creating a new variable, this operator is used. It
remains privately within the block.
Q30)
What is Closure in Perl and how it is helpful?
Ans: It is defined as the block of code in
Perl which is used for capturing the lexical variable which can be accessed at
a later section in a program.
Q31)
What do you understand by Perl scripting?
Ans: It can be regarded as one an important
script programming language similar to that of C and C++ language implemented
in the IT market. It is mainly used for network operations. The use of Perl
scripting depends on the compiler and not on the interpreter. The Perl is used
mainly for network operations, developing websites and OS programs.
Q32) Why
is Perl scripting used?
Ans: Perl Scripting is used for designing 76
operating systems at the same time and 3000 modules. Other functional concepts
can also be done with the help of this programming language. For extending its
support to operating systems and modules, it is also known as comprehensive
perl archive network modules. In simple words, the use of the language is to
extract information from any text file and result in a printing form of the
same by converting the text file.
Q33)
Explain some advantages and disadvantages of programming using Perl script
language?
Ans: Advantages – Perl is a high-level
programming language that is simpler to understand due to its syntax. It is
also easier to use due to its flexibility, and easy readability. In addition,
the language also supports OOP. It also becomes easier to understand since it
has the ability to combine many languages.
Disadvantages
– This software is not portable and has some unreadable codes. It is
slower compared to another programming language since it is an interpretative
language. When you apply any code which is more than 200 lines, it starts to
give in problem within the program. It also contains CPAN module which makes it
incompatible to run on the system in which CPAN is not installed.
Q34)
What is the importance of Perl warnings and how to turn them on?
Ans: In order to check the quality of any
coding in the language, warnings are the basic methods to check the wrong
codes. During the lexical analysis stage, some usual mandatory problems are
highlighted. Therefore, the time spent for researching weird results are very
high which can be minimized by turning on the warnings.
There
are several ways to turn on the warnings.
-w option
is used on the command line for Perl one-liner
-w option
is also used on shebang line on OS such a UNIX or windows. The Windows Perl
interpreter does not require warnings.
For
another operating system, the compiler warnings should be selected.
Q35)
State the difference between Use and Require?
Ans: Both Use and require is used for
importing modules and file extension is not required for any of them.
In case
of use, the objects included are different at the time of compilation and in
case of require, the objects are verified during the runtime.
Q36)
Draw a difference between My and Local?
Ans: Any variable during the coding with My
statement remains in the current block. The variable along with the value goes
out of the block. On the contrary in case of Local statement, it is used to
assign any value to global variable outside the block. The variable of the
local statement can be used globally, but the value lasts till it is inside the
block.
Q37)
Does Perl programming has objects or not?
Ans: The answer to this question is yes, this
programming language has objects that do not force to use it. In most cases,
object-oriented modules can be used without even understanding the object. But
if the program is a large one, then it is required to make it subject oriented.
Q38) How
many types of Perl operators are present?
Ans: This operator is present in four
different types:
1. Unary
operator is similar to that of not operator
2. Ternary operator similar to the conditional operator
3. List operator resembles the print operator
4. Binary operator similar to the additional operator
Q39)
What Perl identifier connotes?
Ans: The identifier is used to state a
variable, module, class, function and other relating objects while using this
programming language. The variable starts with symbols such as @, % or $ which
is followed by digits and underscore.
Q40)
What kind of data is supported by this programming language?
Ans: There are three types of data namely –
arrays of scalars, scalars, and hashes of scalars.
Q41) How
many types of primary data structure are there? What do they denote?
Ans: There are three types of the primary data
structure in this programing language. They are arrays, the scalar, associative
arrays.
1.
Arrays – It is denoted with ‘@’ sign.
2. Scalar – It is capable of holding one information at one time, and it
is denoted by the $ symbol. Further, this symbol is followed by Perl
identifier that can be in the form of underscores or alphanumeric. It should
not start with a digit.
3. Associative arrays – These are also called hashes which work similar to
that of hash tables used by programmers in other languages.
Q42) How
to use a variable in the programming language?
Ans: When you assign a value to a variable
with the help of equal sign, a declaration is made. In case of this language,
there is no need to declare Perl variable to backup memory space within the
application.
Q43)
Explain some features of this programming language?
Ans: Some features of this programming
language are as follows:
1. It is
a simple object-oriented programming syntax
2. It helps in designing Unicode
3. It supports 25,000 open modules at the same time
4. It is an open source software and a cross-platform language
5. It also supports databases such as Oracle, MySQL,
etc.
6. Vital personal data can be protected with the help of this language such as
in e-commerce transactions.
7. It makes use of tools that help in converting a text file into other forms
such that it is compatible with HTML or XML.
8. Regular expression engine is offered by the language that is used for
changing any type of text file
Q44)
Explain the difference between Perl hash and Perl array?
Ans: Perl hash is an unordered list of
elements where is used by the key values. It is symbolized by a % sign.
Perl
array is ordered list of elements used in the programming language which are
used by index numbers and symbolized by @ sign.
Q45) How
to use modules while working with this language?
Ans: A module usually refers to a namespace
which is mentioned in a file. Modules are a collection of function, and there
are certain guidelines that should be followed while implementing the same in
Perl scripting language.
1. The
file name assigned should be same as that of the package name.
2 The name of the package should begin with a capital letter.
3. The file names should have ‘pm’ as its extension.
4. The package should be derived from Exporter class in case no object-oriented
technique is implemented in the module.
5. For the non-object techniques used in the modules, the functions and
variables should be derived from namespace with the help of @EXPORT and
@EXPOR_OK arrays.
Q46) Can
Perl patterns be considered as regular expressions?
Ans: The answer mentioned above is no, the
Perl patterns cannot be considered as regular expressions since the patterns do
not have any references. The regular expression should determine the next state
automation and also keep the previous state into it. Wrong usage of pattern is disqualified
regular expressions.
Q47)
What does Perl array function mean?
Ans: In an array, this function is used to add
or remove elements. This function is available in four different types, they
are
1. Pop
– It helps to remove the last element of an array.
2. Push – This function helps to add a new element at the end of an array.
3. Shift – this function helps to remove the element on the extreme left
on an array.
4. Unshift – To add a new element at the start of an array, this function
is used.
Q48) How
to differentiate Perl list and Perl array?
Ans: The Perl list is a process to bring
together data into the programming source code. This list is a fixed collection
of scalars and this list is always present in the one-dimensional form.
The Perl array is a process to collect data in the form of variables, and these
are multi-dimensional.
Q49) How
many loop control keys are found and what do they connote?
Ans: In this language, there are three types
of loop control statement namely next, redo, and last.
1. Next
statement – It is similar to the continue statement in C language and
helps to move to next element of an array skipping all the elements in between.
2. Redo statement – it helps to restart the current loop without
considering the control statement.
3. Last statement – It functions similar to that break statement in C
language. It helps to exit the loop soon after using the statement.
Q50) How
to get the average of numbers using the programming language?
Ans: First you have to enter the number and
the output of the average number would be shown as the result.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
$sum =
0; $counted
= 0; print
"Enter your choice of number: "; $number
= <>; chomp($number); while
($number >= 0) { $counted++; $sum
+= $number; print
"Enter another number: "; $number
= <>; chomp($number); } print
"$counted numbers were enteredn"; if
($counted > 0) { print
"The average is ",$sum/$counted,"n"; } exit(0); |
Q51)
Explain the use of –i, -n, and –p options?
Ans: Among all the options, -n and –p is used
to include scripts within the loop. The first option is used to enables the
programming language implements the script inside the loop. The –p option
function in the same manner with addition of continuation. The –i option is used
to change the files in the right place. Using this option, the name of the
input file can be changed, and the output file would open with the original
file name. With this option, no backup of any file is created.
Q52)
What does the word subroutine stand for?
Ans: It is a block of code used in the
above-mentioned programming language which is implemented together in order to
task any task. It can be executed at any point in time in any program. To
mention some of its advantages, it helps to execute modular programming making
it simpler to understand. It also helps to eliminate duplication of any program
reusing the same code in the programming language.