1.
What
is CPAN? Its uses?
CPAN
(Comprehensive Perl Archive Network) is a large collection of free
Perl software and documentation
CPAN is also name of the module, which is used to download and install module from the archive.
CPAN is also name of the module, which is used to download and install module from the archive.
2.
What
does “use strict” , “use vars” , “no vars” mean?
#!/usr/local/bin/perl
-w
use strict;
use strict;
1. This
will help you (really, it will force you) to write better, cleaner
code.
Adding
the -w switch to the perl interpreter will cause it to spit out
warnings on uninitialized variables - potential bugs.
'use
strict' turns on the 'strict' pragma which will make you
declare your variables with the my keyword.
'use
strict' also tosses up errors if your code contains any barewords
that can't be interpreted in their current context.
2. vars - Perl pragma to predeclare global variable names (obsolete)
2. vars - Perl pragma to predeclare global variable names (obsolete)
3. no vars - You may not rescind such declarations with no var.
3.
Difference
b/w use and require?
3.
The "require" it there
where you want to use it but don't "use" it(i.e. Use: can't
be called with parens, can't be used in an expression, etc).
example :
example :
- Use DBI;
- require "siva.pm";
4.
What
do the symbols $ @ and % mean when prefixing a variable?
1.
$a
: means it is a variable.
2.
@a
: means
it is an array.
3. %a
: means it is a hash.
5.
What
purpose does each of the following serve: -w, strict, -T ?
#!/usr/local/bin/perl
-w
use strict;
use strict;
This
will help you (really, it will force you) to write better, cleaner
code.
Adding
the -w switch to the perl interpreter will cause it to spit out
warnings on uninitialized variables - potential bugs.
'use
strict' turns on the 'strict' pragma which will make you
declare your variables with the my keyword.
'use
strict' also tosses up errors if your code contains any barewords
that can't be interpreted in their current context.
-T:
Taint
mode is a way of making your code more secure. It means that your
program will be fussier about data it receives from an external
source. External sources include users, the file system, the
environment, locale information, other programs and some system calls
(e.g. readdir).
There
are differing opinions on when to use taint mode. Certainly as a
minimum, any CGI application should use taint mode. When accepting
external data you should always program defensively and use taint
mode to ensure that the external data matches your expectations
6.
Explain
the use of do, require, use, import
do
will call the code, no ifs, ands, or buts, at runtime. This is
usually a bad idea, because if that's happening, you should really
probably be putting it into a subroutine.
While
do() behaves almost identically to require(), it reloads the file
unconditionally. It doesn't check %INC to see whether the file was
already loaded. If do() cannot read the file, it returns undef and
sets $! to report the error. If do() can read the file but cannot
compile it, it returns undef and puts an error message in $@. If the
file is successfully compiled, do() returns the value of the last
expression evaluated.
---------------------
Require:
will call exactly once and then no more, at runtime. it can do it for
a package, too, in which case it will actually go find that package
for you.
require()
reads a file containing Perl code and compiles it. Before attempting
to load the file it looks up the argument in %INC to see whether it
has already been loaded. If it has, require() just returns without
doing a thing. Otherwise an attempt will be made to load and compile
the file.
require()
has to find the file it has to load. If the argument is a full path
to the file, it just tries to read it. For example:
require
"/home/httpd/perl/mylibs.pl";
use
does
everything require does in the package case, then calls import in
that package.
use(),
just like require(), loads and compiles files containing Perl code,
but it works with modules
only and is executed at compile time.
The
only way to pass a module to load is by its module name and not its
filename. If the module is located in MyCode.pm, the correct way to
use() it is: use MyCode
------------------------------ -------------------
import
is
a function defined in a package. it gets called by use,
but it's not otherwise special.
7.
Use
of our, my and local?
My:
non-package variables, private variable, So that the variable cannot
be accessed in the form of $package_name::variable.
Our:
package variables, global variables, they can be accessed outside the
package (or lexical scope) with the qualified namespace, as
$package_name::variable.
Local:
A local modifies its listed variables to be "local" to the
enclosing block, eval, or do FILE --and to any subroutine called from
within that block
8.
Use
of ref function
REF
is just a reference to another reference.
9.
What
are STDIN,STDOUT and STDERR?.
STDIN
- Standard Input, for user control input, typically the
keyboard
STDOUT - Standard Output,for regular use output, typically the screen
STDERR - Standard Error, for error output; typically defaults to the screen too
DATA - Input for data stored after __END__ at the end of the program
STDOUT - Standard Output,for regular use output, typically the screen
STDERR - Standard Error, for error output; typically defaults to the screen too
DATA - Input for data stored after __END__ at the end of the program
10.
@INC
and %INC
The
@INC
array holds all the file system paths where Perl will be looking for
modules when you use or require them. After use or require,
The
%INC
hash will contain the loaded modules and where they were loaded from.
Examples
from my laptop:
@INC:
'/etc/perl',
'/usr/local/lib/perl/5.10.0',
'/usr/local/share/perl/5.10.0' ,
'/usr/lib/perl5',
'/usr/share/perl5',
'/usr/lib/perl/5.10',
'/usr/share/perl/5.10',
'/usr/local/lib/site_perl',
%INC:
'warnings/register.pm' => '/usr/share/perl/5.10/ warnings/register.pm',
'bytes.pm' => '/usr/share/perl/5.10/bytes.pm ',
'XSLoader.pm' => '/usr/lib/perl/5.10/XSLoader. pm',
'Carp.pm' => '/usr/share/perl/5.10/Carp.pm' ,
'Exporter.pm' => '/usr/share/perl/5.10/ Exporter.pm',
'warnings.pm' => '/usr/share/perl/5.10/warnings .pm',
'overload.pm' => '/usr/share/perl/5.10/overload .pm',
'Data/Dumper.pm' => '/usr/lib/perl/5.10/Data/ Dumper.pm'
(%INC
contains Data::Dumper because I used it to quickly dump those two
values).
11.
How
you can invoke shell command? Hint: system(), backtick, exec() in
details
Exec
executes
a command and never
returns.
It's like a return
statement
in a function. If the command is not found exec
returns
false. It never returns true, because if the command is found it
never returns at all. There is also no point in returning STDOUT,
STDERR
or
exit status of the command
System
executes
a command and your Perl script is continued after the command has
finished. The return value is the exit status of the command.
backticks
like
system
executes
a command and your perl script is continued after the command has
finished.
12.
What
is the exact difference between system() and exec() (similar to
question no 11)
13.
Error
handling using eval
you
can
use the eval()
function
to trap the error and avoid ending the script. The eval()
function
accepts an expression and then executes it. Any errors generated by
the execution will be isolated and not affect the main program.
However, all function definitions and variable modifications do
affect the main program.
You
can use the eval()
function
to trap a normally fatal error:
eval
{ alarm(15) };
warn()
if $@;
eval
{ print("The
print function worked.\n"); };
warn()
if $@;
This
program displays the following:
The
Unsupported function alarm function is unimplemented at test.pl line
3.
The print function worked.
14.
Print
the array @arr in reversed case-insensitive order .
#!
/bin/perl
@array
= ("b","f","n","m");
@array
= ( reverse ( sort(@array) ) );
print
"@array"
;
15.
There
are two types of eval statements i.e. eval EXPR and eval BLOCK.
Explain them.
eval
BLOCK
is
used to catch exception. It's called try
in
other languages. It's perfectly safe.
eval
EXPR
is
used to compile and execute code. While it does catch exceptions,
that's not it's main purpose. It should be avoided as much as
possible, and its use should raise big warning flags.
16.
Autoverification
(very
rarely)
17.
Questions
on hash and hash reference
my
%hash
= (1 => 'compile', 2 => 'binary',
3
=> 'ascii', 4 => 'digit');
#
print the hash ordered pairs
foreach
(sort
{$hash{$b} cmp $hash{$a}} keys %hash) {
print "$_:
$hash{$_}\n";
}
%time
= (hour => 12, min =>25, sec => 32, msec =>75);
$size
= scalar keys %time; # explicit scalar context - or
$size
= keys %time; # implicit scalar context - or
$timeRef
= \%time; # using a reference
$size
= keys %$timeRef;
print
"Hash
size: $size\n"; # prints Hash size: 4
c.
How
to refer a hash and how to dereference it
Similar to the array, Perl hash can also be referenced by placing the ‘\’ character in front of the hash. The general form of referencing a hash is shown below. %author = (
'name'
=> "Harsha",
'designation'
=> "Manager"
);
$hash_ref
= \%author;
This
can be de-referenced to access the values as shown below.
$name
= $ { $hash_ref} { name };
d.
Nesting
of hash
A
multidimensional hash is the most flexible of Perl's nested
structures. It's like building up a record that itself contains other
records.
%HoH
= (
flintstones => {
husband
=> "fred",
pal
=> "barney",
},
jetsons => {
husband
=> "george",
wife
=> "jane",
"his boy"
=> "elroy", # Key quotes needed.
},
simpsons => {
husband
=> "homer",
wife
=> "marge",
kid
=> "bart",
},
);
18.
Chomp
and chop
Chop:
removes
from argument last character of string.
Chomp:
removes from argument last character of string if it is return.
19.
Explain
qw,qq,qx (what’s its use, when to use)
qw:
Quote-like
operator. Takes a string as parameter and builds a quoted list.
@array = qw{red blue yellow};
20.
What
are the different ways to concatenate strings in Perl
Using ${name}
$name
= 'foo';
$filename
= "/tmp/${name}.tmp";
using Perl's dot operator
$name
= checkbook';
$filename
= '/tmp/' . $name . '.tmp';
#
$filename now contains "/tmp/checkbook.tmp"
using Perl's join function
$name
= 'checkbook';
$filename
= join '', '/tmp/', $name, '.tmp';
#
$filename now contains "/tmp/checkbook.tmp"
Perl lets you define your own functions to be called like Perl's built-in functions.
Declared as Called as
sub mylink ($$) mylink $old, $new
Since prototypes are taken into consideration only at compile time, it naturally falls out that they have no influence on subroutine references like\&foo or on indirect subroutine calls like &{$subref} or $subref->()
Pass an array to subroutine:
There are two ways you can do this:
by prototype
by reference
But before I discuss these--if what you show in your question is about the extent of what you want to do--let me suggest List::MoreUtils::pairwise
So, where you would write this:
my @sum = two_array_sum( @a, @b )
You'd simply write this:
my @sum = pairwise { $a + $b } @a, @b;
By prototype
This works like push. (And just like push it demands to have a @ sigil on something)
sub two_array_sub (\@\@) {
my ( $aref, $bref ) = @_;
...
}
That way when you do this
two_array_sub( @a, @b );
it works. Whereas normally it would just show up in your sub as one long list. They aren't for everybody as you'll see in my discussion below.
By reference
That's the way that everybody is showing you.
some_sub( \@a, \@b );
About prototypes
They're finicky. This won't work if you have refs:
two_array_sub( $arr_ref, $brr_ref );
You have to pass them like this:
two_array_sub( @$arr_ref, @$brr_ref );
However, because making "array expressions" gets really ugly quickly with arrays nested deep, I often avoid Perl's fussiness as you can overload the type of reference Perl will take by putting it in a "character class" construct. \[$@] means that the reference can either be a scalar or array.
sub new_two_array_sub (\[$@]\[$@]) {
my $ref = shift;
my $arr = ref( $ref ) eq 'ARRAY' ? $ref : $$ref; # ref -> 'REF';
$ref = shift;
my $brr = ref( $ref ) eq 'ARRAY' ? $ref : $$ref;
...
}
So all these work:
new_two_array_sub( @a, $self->{a_level}{an_array} );
new_two_array_sub( $arr, @b );
new_two_array_sub( @a, @b );
new_two_array_sub( $arr, $self->{a_level}{an_array} );
However, Perl is still fussy about this... for some reason:
new_two_array_sub( \@a, $b );
OR
new_two_array_sub( $a, [ 1..3 ] );
Or any other "constructor" that still could be seen as a reference to an array. Fortunately, you can shut Perl up about that with the old Perl 4 &
&new_two_array_sub( \@a, [ 1..3 ] );
Then the mux-ing code in the sub takes care of handling two array references.
21.
Functions
on array: Push, pop, shift, unshift, join, split, splice
Push: push (ARRAY, LIST)- adds LIST to the end of a given array, and returns the new number of elements in the array. POP: pop (ARRAY) Perl pop function is used to remove and return the last element of an array. Shift: Perl shift function removes and returns the first element of an array, shortening the dimension of the array with 1. Unshift: The Perl unshift function inserts a list at the beginning of an array and returns the number of elements of the array after the insertion. Join: Perl join function is used to concatenate the elements of an array. Split: Perl split function allows you to break up a string into an array or a list, by using a specific pattern. Splice: The Perl splice function is for arrays and is used to remove, replace or add elements.
22. Different hash functions like each, keys, values, exists, delete
removes
a
key-value pair from a hash; you can delete an individual element
of a hash or a hash slice.
|
|
returns
a two-element list that contains a (key, value) pair from a hash
or a (index, value) pair from an array
|
|
it
checks whether a particular hash/array element or a subroutine
exists
|
|
use
this function to get the indices of an array or the keys of a hash
|
|
use
this function to get the values of an array or a hash
|
Sort
of Hash by hash value:
#
define a hash
my
%hash
= (1 => 'compile', 2 => 'binary',
3
=> 'ascii', 4 => 'digit');
#
print the hash ordered pairs
foreach
(sort
{$hash{$b} cmp $hash{$a}} keys %hash) {
print "$_:
$hash{$_}\n";
}
24.
How
to set Environment variables in Perl (Hint: %ENV)
$ENV{'HOME'}
= '/path/to/new/home';
25.
Use
of map and grep functions in Perl
Map
: The
Perl map
function
evaluates a block or an expression for each element of an array and
returns a new array with the result of the evaluation
Grep:
Perl grep
function
is used to filter a list and to return only those elements that match
a certain criteria - in other words it filters out the elements which
don’t match a condition. Normally, the function will return a list
that contains less elements then the original list
26.
What
is the difference between die and exit in perl
1)
die is used to throw an exception (catchable using eval). 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.
exit will set the error code based on its argument.
3)
die outputs a message exit does not.
27.
Array
with repeating digits. Sort and print digits with no of counts. Ex:
@arr = (1,2,4,6,3,1,2,6,8,3,4,9,1,2, 4). Output should be @arr =
(1,1,1,2,2,2,3,3,4,4,4,6,6,8, 9) ). You can’t use hash feature.
Think about optimization too.
28.
Decimal
to binary (program)
$decimalnum = bin2dec($binarynum);
# Convert a binary number to a decimal number
sub bin2dec {
unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
}
29.
How
to find which method is being invoked or being called in Perl and in
which method you are currently? Hint: caller()
Returns information about the current
subroutines caller. In a scalar context, returns the caller's package
name or the package name of the caller EXPR steps up.
($package, $filename, $line) = caller;
($package, $filename, $line, $subroutine,$hasargs, $wantarray, $evaltext, $is_require) = caller($i);
30.
Explain
the use of caller and wantarray function?
wantarray
wantarray is a special keyword which returns a flag indicating which context your subroutine has been called in.
It will return one of three values.
true: If your subroutine has been called in list context
false: If your subroutine has been called in scalar context
undef: If your subroutine has been called in void context
For example:-
You have a subroutine named "display" and from that subroutine sometimes you want to return an array and sometimes a scalar.
So the syntax would be
sub display(){
return(wantarray() ? qw(A B C) : '1');
}
my @ab = display();
my $bd = display();
then output is
#@ab = (A B C);
and
#$bd = 1;
The output will be depend upon the left hand side
assignment. If you put an array (@ab) it will call
wantarray() else a scalar value will return.
wantarray
wantarray is a special keyword which returns a flag indicating which context your subroutine has been called in.
It will return one of three values.
true: If your subroutine has been called in list context
false: If your subroutine has been called in scalar context
undef: If your subroutine has been called in void context
For example:-
You have a subroutine named "display" and from that subroutine sometimes you want to return an array and sometimes a scalar.
So the syntax would be
sub display(){
return(wantarray() ? qw(A B C) : '1');
}
my @ab = display();
my $bd = display();
then output is
#@ab = (A B C);
and
#$bd = 1;
The output will be depend upon the left hand side
assignment. If you put an array (@ab) it will call
wantarray() else a scalar value will return.
31.
How
will you find line number, package and a file name in Perl? (Hint:
__FILE__, __LINE__, __PACKAGE__)
ctives
only apply to where they are written, so you can not encapsulate their
effect in a subroutine. (unless you wanted a sub that only prints info
about where it is defined)
The
special literals __FILE__, __LINE__, and __PACKAGE__ represent the
current filename, line number, and package name at that point in your
program. They may be used only as separate tokens; they will not be
interpolated into strings. If there is no current package (due to an
empty package; directive), __PACKAGE__ is the undefined value.
The
caller
function will do what you are looking for:sub print_info {
my ($package, $filename, $line) = caller;
...
}
print_info(); # prints info about this line
This will get the information from where the sub is called, which is probably what you are looking for. The __FILE__
and __LINE__
dire
32.
How
to install a Perl Module from CPAN
perl -MCPAN -e shell
install DBD::mysql
Perl lets you define your own functions to be called like Perl's built-in functions.
Declared as Called as
sub mylink ($$) mylink $old, $new
Since prototypes are taken into consideration only at compile time, it naturally falls out that they have no influence on subroutine references like\&foo or on indirect subroutine calls like &{$subref} or $subref->()
Pass an array to subroutine:
There are two ways you can do this:
by prototype
by reference
But before I discuss these--if what you show in your question is about the extent of what you want to do--let me suggest List::MoreUtils::pairwise
So, where you would write this:
my @sum = two_array_sum( @a, @b )
You'd simply write this:
my @sum = pairwise { $a + $b } @a, @b;
By prototype
This works like push. (And just like push it demands to have a @ sigil on something)
sub two_array_sub (\@\@) {
my ( $aref, $bref ) = @_;
...
}
That way when you do this
two_array_sub( @a, @b );
it works. Whereas normally it would just show up in your sub as one long list. They aren't for everybody as you'll see in my discussion below.
By reference
That's the way that everybody is showing you.
some_sub( \@a, \@b );
About prototypes
They're finicky. This won't work if you have refs:
two_array_sub( $arr_ref, $brr_ref );
You have to pass them like this:
two_array_sub( @$arr_ref, @$brr_ref );
However, because making "array expressions" gets really ugly quickly with arrays nested deep, I often avoid Perl's fussiness as you can overload the type of reference Perl will take by putting it in a "character class" construct. \[$@] means that the reference can either be a scalar or array.
sub new_two_array_sub (\[$@]\[$@]) {
my $ref = shift;
my $arr = ref( $ref ) eq 'ARRAY' ? $ref : $$ref; # ref -> 'REF';
$ref = shift;
my $brr = ref( $ref ) eq 'ARRAY' ? $ref : $$ref;
...
}
So all these work:
new_two_array_sub( @a, $self->{a_level}{an_array} );
new_two_array_sub( $arr, @b );
new_two_array_sub( @a, @b );
new_two_array_sub( $arr, $self->{a_level}{an_array} );
However, Perl is still fussy about this... for some reason:
new_two_array_sub( \@a, $b );
OR
new_two_array_sub( $a, [ 1..3 ] );
Or any other "constructor" that still could be seen as a reference to an array. Fortunately, you can shut Perl up about that with the old Perl 4 &
&new_two_array_sub( \@a, [ 1..3 ] );
Then the mux-ing code in the sub takes care of handling two array references.
.
You
have two arrays. Say @arr1 = (1,2,5,6) and @arr2 = (3,4) We need to
put the element of @arr2 at @arr1 in such a way that @arr1 would
become @arr1= (1,2,3,4,5,6) without using third array. Hint:
use splice function
The Perl splice function is for arrays and is used to remove, replace or add elements.
35.
Inbuilt
special variable like $!, $? Etc
Per-filehandle Special Variables | ||
---|---|---|
These variables never need to be mentioned in a local()because they always refer to some value pertaining to the currently selected output filehandle - each filehandle keeps its own set of values. | ||
Variable | Contents | Mnemonic |
$| | If set to nonzero, forces a flush after every write or print | When you want your pipes to be piping hot |
$% | Current page number | % is page number in nroff |
$= | Current page length | = has horizontal lines |
$- | Number of lines left on the page | lines_on_page - lines_printed |
$~ | Name of the current report format | Closely related to $^ |
$^ | Name of the current top-of-page format | Points to top of page |
Local Special Variables | ||
---|---|---|
These variables that are always local to the current block, so you never need to mention them in a local(). All of them are associated with the last successful pattern match. | ||
Variable | Contents | Mnemonic |
$1..$9 | Contains the subpattern from the corresponding set of parentheses in the last pattern matched | like \1..\9 |
$& | Contains the string matched by the last pattern match | like & in some editors |
$` | The string preceding whatever was matched by the last pattern match, not counting patterns matched in nested blocks that have been exited already. | ` often precedes a quoted string in normal text |
$' | The string following whatever was
matched by the last pattern match, not counting patterns matched in
nested blockes that have been exited already. For example: $_ = 'abcdefghi'; /def/; print "$`:$&:$'\n"; # prints abc:def:ghi |
' often follows a quoted string in normal text |
$+ | the last bracket matched by the last search pattern. This is useful if you don't know which of a set of alternative patterns matched. For example: /Version: (.*)|Revision: (.*)/ && ($rev = $+); | be positive and forward looking |
Global Special Variables | ||
---|---|---|
There are quite a few variables that are global in the fullest sense -- they mean the same thing in every package. If you want a private copy of one of them, you must localize it in the current block. | ||
Variable | Contents | Mnemonic |
$_ | The default input and pattern-searching space. The following pairs are equivalent: while (<>) {... # equivalent only in while! while ($_ =<>) {... /^Subject:/ $_ =~ /^Subject:/ y/a-z/A-Z/ $_ =~ y/a-z/A-Z/ chop chop($_) | underline is understood to be underlying certain undertakings |
$. | The current input line number of the last filehandle that was read. Rember that only an explicit close on the filehandle resets the line number. | many programs use . to mean the current line number |
$/ | The input record separator, newline by default. $/ may be set to a value longer than one character in order to match a multi-character delimiter. If $/ is undefined, no record separator is matched, and<FILEHANDLE> will read everything to the end of the current file. | / is used to delimit line boundries when quoting poetry. Or, if you prefer, think of mad slashers cutting things to ribbons. |
$\ | The output record separator for the print operator. | You set $\ instead of adding \n at the end of the print. |
$, | The output field separator for the print operator. | What is printed when there is a , in yourprint statement |
$" | This is similar to $, except that it applies to array values interpolated into a double-quoted string (or similar interpreted string). Default is space. | Obvious, I think |
$# | The output format for numbers display via the printoperator | # is the number sign |
$$ | The process number of the Perl running this script | Same as shells |
$? | The status returned by the last pipe close, backtick(``) command or system operator. Note that this is the status word returned by the wait() system call, so the exit value of the subprocess is actually ($? >>*). $? & 255 gives which signal, if any, the process died from, and whether there was a core dump. | Similar to sh and ksh |
$* | Set to 1 to do multi-line matching within a string, 0 to tell Perl that it can assume that strings contain a single line, for the purpose of optimizing pattern matches. Default is 0 | * matches multiple things |
$0 | Contains the name of the file containing the Perl script being executed. Depending on your OS, it may or may not include the full pathname. | Same as sh and ksh |
$[ | The index of the first element in an array, and of the first character in a substring. | [ begins subscripts |
$] | The first part of the string printed out when you sayperl -v. It can be used to determine at the beginning of a script whether the Perl interpreter executing the script is in the right range of versions. If used in a numeric context, $] returns version + patchlevel /1000. | Is this version of Perl in the "rightbracket"? |
$; | The subscript separator for multi-dimensional array emulation. If you refer to an associative array element as: $foo{$a,$b,$c} it really means: $foo{join($;, $a, $b, $c)} but don't put @foo{$a,$b,$c} which means ($foo{$a},$foo{$b},$foo{$c} | Comma (the syntactic subscript separator) is a semi-semicolon. Yeah, it's pretty lame, but $, is already taken for something more important. |
$! | If used in a numeric context, yields the current value of errno, with all the usual caveats. (This means that you shouldn't depend on the value of $! to be anything in particular unless you've gotten a specific error return indicating a system error.) If used in a string context, yields the corresponding sysem error string. | What just went bang? |
$@ | The Perl syntax error or routine error message from the last eval, do-FILE, or require command. If set, either the compilation failed, or the die function was executed within the code of the eval. |
36.
Piping
in and piping out in Perl
A pipe is
a unidirectional I/O channel that can transfer a stream of bytes from
one process to another. Pipes come in both named and nameless varieties.
You may be more familiar with nameless pipes, so we'll talk about those
first.
Anonymous Pipes
Perl's open function opens a pipe instead of a file when you append or prepend a pipe symbol to the second argument to open.
This turns the rest of the arguments into a command, which will be
interpreted as a process (or set of processes) that you want to pipe a
stream of data either into or out of. Here's how to start up a child
process that you intend to write to:
open SPOOLER, "| cat -v | lpr -h 2>/dev/null"
or die "can't fork: $!";
local $SIG{PIPE} = sub { die "spooler pipe broke" };
print SPOOLER "stuff\n";
close SPOOLER or die "bad spool: $! $?";
This example actually starts up two processes, the first of which (running cat) we print to directly. The second process (running lpr) then receives the output of the first process. In shell programming, this is often called a pipeline. A pipeline can have as many processes in a row as you like, as long as the ones in the middle know how to behave like filters; that is, they read standard input and write standard output.
37.
How
to implement stack and queue in Perl?
use push, pop,shift,unshift function
use push, pop,shift,unshift function
38.
How
to find the list of installed modules in Perl?
command:
pmall
instmodsh
perl -MNet::Ping -e 1
command:
pmall
instmodsh
perl -MNet::Ping -e 1
39.
Use
of BEGIN and END block.
There are two special code blocks for perl modules - BEGIN and END. These blocks are executed when a module is first loaded, and when the perl interpreter is about to unload it, respectively.
Here's an example for a logging module that makes use of this facility:
# File : MyLog.pm # package MyLog; use strict; use warnings; BEGIN { open MYLOG, ">", "mylog.txt"; } sub log { my $what = shift; # Strip the string of newline characters $what =~ s/\n//g; # The MYLOG filehandle is already open by virtue of the BEGIN # block. print MYLOG $what, "\n"; } END { close(MYLOG); } 1;
40.
Simulate
the behaviour of ‘use lib’ pragma using BEGIN block.
use lib "$ENV{HOME}/libperl"; # add ~/libperl
no lib "."; # remove cwd
This pragma simplifies the manipulation of @INC at compile time. It is typically used to add extra directories to Perl's search path so that later do, require, and use statements will find library files that aren't located in Perl's default search path.
File
Handling in Perl
1.
File
Testing. Binary or text, size, accessed like –e, -f, -a, -c –m
etc
$neededfile="myfile.cgi";
if (-e $neededfile)
{
#proceed with your code
}
Writable: -w
Executable: -x
$neededfile="myfile.cgi";
if (-e $neededfile)
{
#proceed with your code
}
File exists, has a size of zero: -z
File exists, has non-zero size: -s
Readable: -rFile exists, has non-zero size: -s
Writable: -w
Executable: -x
You can test the file to see if it is text or if it is binary using these:
Text File: -T
Binary File: -B
Binary File: -B
2.
Use
of the special file handle
_.
(Note : its just _ not $_). Using this can significantly improve
performance in many cases.
sub _() as a means to localise text
sub _() as a means to localise text
3.
Syntax
for opening, appending, reading, writing files
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);
4.
How
to assign File handle into an array instead of using while loop?
foreach $file (@filehandles) { print $file "File $count"; close $file; $count++; }
foreach $file (@filehandles) { print $file "File $count"; close $file; $count++; }
5.
How
to delete a file?
print "content-type: text/html \n\n"; #The header @files = ("newtext.txt","moretext.txt","yetmoretext.txt"); foreach $file (@files) { unlink($file); }
6.
How
to copy or move a file?
use File::Copy qw(copy);
copy $old_file, $new_file;
use File::Copy qw(move);
move $old_name, $new_name;
use File::Copy qw(copy);
copy $old_file, $new_file;
use File::Copy qw(move);
move $old_name, $new_name;
7.
What
the various file permissions (flags) in Perl?
8. Given a file, count the word occurrence (case insensitive)
open(FILE,"filename");
@array=<FILE>;
$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";
9. Displaying file contents using hash in Perl
my %hash;
while (<FILE>)
{
chomp;
my ($key, $val) = split /=/;
$hash{$key} .= exists $hash{$key} ? ",$val" : $val;
}
This walks through every line splitting on the '=' sign and either adds an entry or appends to an existing entry in the hash table.
< or r | Read Only Access |
> or w | Creates, Writes, and Truncates |
>> or a | Writes, Appends, and Creates |
+< or r+ | Reads and Writes |
+> or w+ | Reads, Writes, Creates, and Truncates |
+>> or a+ | Reads, Writes, Appends, and Creates |
open(FILE,"filename");
@array=<FILE>;
$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";
9. Displaying file contents using hash in Perl
my %hash;
while (<FILE>)
{
chomp;
my ($key, $val) = split /=/;
$hash{$key} .= exists $hash{$key} ? ",$val" : $val;
}
This walks through every line splitting on the '=' sign and either adds an entry or appends to an existing entry in the hash table.