Perl Quick Reference Card
Perl Cheat Sheet
http://www.cheat-sheets.org/
Perl Cheat Sheet
http://techcheatsheets.com/tag/perl/
Regular Exp in Perl
Perl Reg Exp Tutorial
Perl Regular Expressions by Example
Perl: Matching using regular expressions
Using Perl, how can I replace all whitespace in a file with newlines?
Trim whitespaces begining and end
Whitespace and perl developers
Perl Regular Expressions
Cheat Sheet and Interview Questions
1. What arguments do you frequently use for the Perl interpreter and what do they mean?
2. What does the command ‘use strict’ do and why should you use it?
3. What do the symbols $ @ and % mean when prefixing a variable?
4. What elements of the Perl language could you use to structure your code to allow for maximum re-use and maximum readability?
5. What are the characteristics of a project that is well suited to Perl?
6. Why do you program in Perl?
7. Explain the difference between my and local.
8. Explain the difference between use and require.
9. What’s your favorite module and why?
10. What is a hash?
11. Write a simple (common) regular expression to match an IP address, e-mail address, city-state-zipcode combination.
12. What purpose does each of the following serve: -w, strict, -T ?
13. What is the difference between for & foreach, exec & system?
14. Where do you go for Perl help? "> $name = ""bam"";
> $$name = 1; # Sets $bam
> ${$name} = 2; # Sets $bam
> ${$name x 2} = 3; # Sets $bambam
> $name->[0] = 4; # Sets $bam[0]
symbolic reference means using a string as a reference."
15. Name an instance where you used a CPAN module. "@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.
-------------------------------------------------------------------------------------------------------------------
Package NewModule;
use Exporter; # an application by ‘use’ operator.#
This Exporter package has @ISA array to look for a specific method this array keeps track of classes it is inheriting.
@ISA qw(Exporter);
@EXPORT qw(VAR1 VAR2 VAR3);
# The symbols VAR1 VAR2 VAR3 loaded by default
@EXPORT_OK qw(VAR4 VAR5);
# the symbols VAR4 and VAR5 only loaded if there is a request."
16. How do you open a file for writing? "use XYZ;
my $objref XYZ->new();"
17. How would you replace a char in string and how do you store the number of replacements? "Explain the difference between ""my"" and ""local"" variable scope declarations. ?
Both of them are used to declare local variables.
The variables declared with ""my"" can live only within the block it was defined and cannot get its visibility inherited functions called within that block, but one defined with ""local"" can live within the block and have its visibility in the functions called within that block.
The variables declared with my() are visible only within the scope of the block which names them. They are not visible outside of this block not even in routines or blocks that it calls. local() variables on the other hand are visible to routines that are called from the block where they are declared. Neither is visible after the end (the final closing curly brace) of the block at all.
Perl supports three scoping declarations that enable to create private variables (using my) selectively global variable (using our) and temporary copies of selected global variables (using local) ... my declares a variable to be scoped within the current block and when the block ends the varaible goes out of scope.. ""local"" is an temporary value to an gobal variable and the value lasts only for the duaration of the block it's just has an temporary value while it's being used within that block...
1) My
My creates a new variable and gives a lexical scope for that variable. The variable is not visible outside the block in which it is defined.
2) Local
Local saves the value of a global variable. It never creates a new variable. Here also the variable is not accessible outside the block but it is visible in the subroutine which is called from the original block. My is more preferring than local . But in various places local is useful where my is illegal
1) Changing the meaning of a special variable like $/
2) Localized file handles
3) Globing"
18. When would you not use Perl for a project? ": s/&zeta1;/ xcexb6 /gthis is working fine in vi.. u want it to rit as a perl code using some match for substitution?see for only some char which are taken as special meaning by perl u have to escape it using ' other wise it will replace nything u want.'
~s/&zeta1;/ xcexb6 /g; is working Fine. If there is any special character use in front of it.......
Then use escape character..
suppose / is the part of string then you can write like / where is escape character
: s/sunil/kartikey/kartikey/sunil/g"
What is the Use of Symbolic Reference in PERL? "Perl is easy fast and its fun to code in perl.
Perl is rich with various packages N/w programming is very easy and there are lot more advantages to say.
Its portable i.e. it can be run Windows / Linux / Solaris and Unix with no changes or with minimum changes.
Unlike othere programming languages Perl has builting support for regex.
just cut down your peice as fast as you can with regex ( If you are master in regex ).
It is having the features of scripting (Shell) as well as programming (like C). Using PERL you can easily do the system administration works where comparitively difficult with Shell script.
* PERL is programmer friendly. It is easy to code and can do it in less number of lines. It does all the nice things with minimum fuzz.
* Text manipulation is unmatched.
* It has built-in regex.
* Has the support of world's largest archive of modules(CPAN)"
"What's the significance of @ISA, @EXPORT @EXPORT_OK
%EXPORT_TAGS list & hashes in a perl package?
With example?" "Refer perldoc. On the command line give perldoc command with various options like e.g.-f function name for function help etc.--Manjusha
I use search.cpan.org or the several Perl books from O'Reily. They are also available online through O'Reily's Safari service and older versions are published as the PERL Bookshelf.
-> perldoc -f function name
Ex: perldoc -f print
perldoc is best help to perl."
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? "Hi
The faviurite module is undoubtly CGI.pmIt simplifies the coding as we no need to worry about the intricacies involving the form processing etc.Thanks Abhishek jain"
Explain the difference between "my" and "local" variable scope declarations. ? CGI DBI etc are very common packages used from CPAN. there are thousands of other useful modules.
"I would like to replace some entities in the text file with symbols using Perl.
This is working fine for some special symbols but for the characters such as Zeta we should use Unicode/Hexadecimal values - xcex96. We are doing like this s/&zeta1;/""xcexb6""/g; . This is working fine only for 2 characters such as xb6. How to use this in Perl? How to make use unicode value for zeta in Perl.
Any kind of help will be appreciated." It provides a GUI
Why do you program in PERL "It is a formatter print it in double quotes to see what I mean.
$^ - Holds the name of the default heading format for the default file handle. Normally it is equal to the file handle's name with _TOP appended to it.
According to the book Perl core language-Little black book $^0 holds the name of the operating system for which the current perl was built.
STDOUT_TOP is the output if we print '$^0 in a console."
Where do you go for perl help? "When:
- There's a lot of text processing
- Web-based applications
- Fast/expidient development
- Shell scripts grow into libraries
- Heavy Data manipulation (auditing accounting checking etc... backend processing)
- Data extraction
- transform
- loading (database etc.)
- System admin etc...
When you are developing an application for a real time system in which processing speed is of utmost importnace"
Whats' your favourite module in PERL and why?
Name an instance you used in CPAN module? package PackageName;
what is a Tk module? WHere it is used? What's the use of it? Plse tell me .. "use POSIX;
use lib qw(/library/perl);
use DBI qw(:sqltypes);
what does this mean '$^0'? tell briefly plse.. $varname="VarCharValue"; OR $varname ="$anotherVar" OR $varname='NumberContant';
when do you not use PERL for a project? $VarName = "$LogDir/FileName.log.".UnixDate(ParseDate("today"), "%m%d"
Defining a package sub { }
Use a library "print ""-----msg----\n"";
Defining a variable and init the same my $varName = "value";
Appending time to log file package::subroutine()
Concatenation operator my $varDate = strftime('%Y-%m-%d %T %Z', localtime);
functions/subroutines $varName = shift(@_);
Print a message printf "[strftime('%Y-%m-%d %T %Z', localtime)] $message\n";
Assigning value to a local variable printf STDERR
Calling a subroutine in a package $#_
Get current time stamp if ($#_ >= 0)
Navigate thru an array time + 3600
Print message with time stamp @Array = localtime $now;
Print on STD ERROR $var = sprintf "%d%02d%02d"
Check no of params $Array[n]
Check if no of params > 0 my $var = new Date::Function(Param=>$var);
Date Time Addition if ($var != "")
Store local time in a array $element->sub();
Print formated time in an array "my $dbh = DBI->connect(""DBI:Oracle:SID"", ""user"", ""pwd"")
die ""Cannot connect to database. "" . DBI->errstr;
my $sql = ""select to_char(to_date(?,'YYYYMMDD'),'YYYYMMDD') from dual"";
my $g = $dbh->prepare($sql)
die ""Cannot prepare query. "" . DBI->errstr;
$g->bind_param(1,$abc, SQL_VARCHAR);
$g->bind_param(2, $id, SQL_INTEGER);
$g->execute
die ""error in shell::execute: $!"";
while ( ($row) = $g->fetchrow_array() )
{
$PortList{$row} = $count;
$count = $count + 1;
}
$g->finish();
return %VarList;"
Refering to nth element in a array sub routineName { return $var }
Call Package Function with Param "while ( ($row) = $g->fetchrow_array() )
{
$count = $count + 1;
$rule = $row;
}"
To check if the variable is blank "open(INDATA, ""$Dir/$FileName"") or die ""Cannot Open Command Pipe $Dir/$FileName"";
open(OUTFILE, "">$Dir/$FileName"") or die ""Cannot open Output file $Dir/FileName"";"
Call a Package subroutine $var == 1
DB Call syntax "sub getValue
{
my $sql = ""select * from table"";
my $g = $dbh->prepare($sql)
die ""Cannot prepare query. "" . DBI->errstr;
$g->execute
die ""error in sth::execute: $!"";
my @dbResult;
while ( (@row) = $g->fetchrow_array() )
{
push(@dbResult, join(',',@row));
}
$g->finish();
return (@dbResult);
};
Subroutine syntax "open(OUTFILE, "">>"" . ""$ARGV[0]"") or die ""Cannot open Output file $ARGV[0]"";
printf OUTFILE ""\n"";
close(OUTFILE);"
While #!/usr/local/bin/perl
Open File Create connection to Oracle Db
Comparison to no system($Path . $script . " " . $file . " >> ". $Log. $yyyymmdd . " 2>&1 &"
Perl to fetch resultset
Add new line charater at the end of the file
First Line
Create connection to Oracle Db
Call a script in Perl
Tutorial Cheat Sheet
Shebang line is the first line starting with #!
Escape charaters
\n new line
\t tab
\r carriage return begin of the current line
\$ end of the current line
\"
\\
\'
\
, = concatenate
printf("Welcome to Perl \n"); = printf "Welcome to Perl \n";
chomp $num1 removes return character at the end
$ scalar variable
$number1 =;
Arithmetic Operators
Addition
Operator Precedence (order of evaluation)
*/^ same level left to right for different operators
exponential Right to left
() left to right
+ - last
$c = +7
post and pre increment
$c++
++$c
Associativity of Operators (direction left to right or right to left)
relational operation
== equality = assignment
numeric & string content, and undef example
if add cannot be done no to a string & string cannot be converted into a number then its final result is 0
. Is used for concatenation
Perl Regular Expression
. Evaluates num into string
concatenation . , + tries to conv till cannot
Top10' does not start with no
10Top10' = 20 start with no
Perl is case sensitive
use strict
numeric context undef var = 0
string context undef var = empty
Control Structure
do while vs do until
To compare nos use = < >
To compare strings use eq lt gt
Perl is not a strict data type
ternary operator ? _:_
Arrays & Hashes
Define a array @
Refer individual element $ c[0] $c[1]
Array starts from index 0
@array = { 'sales', 283, "three", 16.439};
Creating and looping
assignment
$array[0] = "Happy";
printf "@array \n"
print "@array \n";
print @array, "\n";
qw operator
@array = qw (this is an array);
print "\n array \n";
@array = {2 .. 5};
$#
$array[$#array]
$# gives last index no gives 9
printf "There are" , scalar(@array), "elements in \@array \n";
gives 10
Negative subscript
$array [-4] 4th element from last
$# array= 4 reduce size to 4
$array = { }; blank out the array
array slices &
@array = qw (zero one two …… nine};
print "@array \n\n";
print "@array[1,3,5,7,9] \n";
{$chiquita , $dole } ={"banana", "pineapple"};
print "\$chiquita = $chiquita \n \$dole=$dole \n";
print "@array \n\n";
{$chiquita, $dole } = {$dole, $chiquita};
print "After swapping values \n";
print "\$chiquita = $chiquita \n \$dole=$dole \n";
push, pop, shift, unshift, functions (stack)
insert extract
begin last
push (@array, $i); push at the end
$elem = pop (@array); push the last element
shift unshift
begin begin
FIFO
1
12
1 2 3
1 2
1
LIFO
1
2 1
3 2 1
2 1
1
Resources : Perl Camel bks
Keywords
undef
? :
qw operator can take array values with spaces
..
push
pop
shift
unshift
scalar
$#
, . +
= eq
= ==
chomp
shebang
\
@array
$array
Splice function
to replace (part of an array)
@replaced = splice (@array , 5, scalar(@array2), @array2);
@removed = splice (@array, 15, 3);
@chopped = splice (@array, 8);
splice (@array);
unless (@array);
{print "\@array has no elements remaining \n"; }
sort array
@reversed = reverse (@array);
@array = {100,23, 9,75,5,10,2,50};
@sorted lexically = sort @array2;
@sortedNumerically = sort {$a < => $b } @array2;
Linear Search / Binary Search
Hash Create and Access hash elements (key value pairs)
%hash ={width =>'300'
height =>'150');
print "\$hash['width'] = $hash['width']\n"
hash are not interpretated when included in " "
print "%hash \n"
print %hash, "\n";
%hash = (one => "I", two => "II")
%hash ={"I", "II")
Using key value each reverse
@keys = keys (% presidents);
while ($key = pop(@key))
{print "$key => $presidents $key} \n";
@values = values(%presidents);
%hash = reverse(%presidents);
each extract key value pairs
while (($key , $value) = each (%presidents));
print "$key => $value \n";
heap = garpage collector
stack = till in scope
Using delete, exists,defined
delete ($hash('Joe')); don’t have to init index increment and terminating condi, perl uses it own index
search any collection
Control Structures
foreach $number ( @array ) manipulations
"foreach $name('Amanda', 'Jeff', 'Sarah')
print ""$name"";
print ""$_"";
print;
all 3 prints the same output"
push (@smallNumbers, $_) if $_ < 6;
@smallNumbers2 = grep( $_ < 6, @numbers) ; continue
push (@doubleNumbers, $_ * 2); goto
@doubledNumbers2 = map( $_ * 2, @numbers); break
foreach ( sort keys (%hash ) ) { print "$_\t", "*" x continue the outer loop without testing
for labels
next exit
next LABEL;
last
redo
"blocks
LABEL: for ( $num = 1; $num <= 10; ++$num ) { next LABLE if ( $num % 2 ==0 ); print ""$num ""; }"
die default scalar variable
subroutines and functions default array
Functions
sub subroutine1 {} shifts arguments
subroutine1 ()
print "$_[$i]"
@_ calling subroutine not defined before use
"displayarguments( ""Sam"", ""Jones"");
sub displayarguments
{
print ""All arguments : @_ \n"";
for
{print ""$_[$i]""}}" not allowed () are required
shift()
for (1 .. 10) { print square ($_), " "; } sub queue { $value = shift(); return $value ** 2; } function to generate a random number
return can return multiple values
&defineBeforeWithoutArguments(); global variable
&defineBeforeWithoutArguments; local, pass by reference
&defineBeforeWithArguments(1,2,3); local, pass by value
rand() packages
srand() eq to import in java, include in c, using c#
our package.variable
my
local
perl modules
require tilt
$main::variable
use strict;
use warnings;
regular expression also returns no of replacements
~ to find digit in the string
if $string =~ m/snow/;
=~ s/world/planet/; digit
same as s(world)(planet); word
s/world/planet/g; white space
/\d/ alpha numeric
/[0-9]/ any non word
\d any non white space
\w and
\s =
\D <>
\W
\S
&&
=~
!~
m/hello
hi there/ 0-1
m/(hello|hi) there/ 1 or more
s/1\d*1/22/; 0 or more
s/1\d+1/22/;
s/1\d?1/22/;
?
+
*
pattern*
pattern+
pattern? first look behind assertion (?<=i ) tests whether the string matched I right before it matched "be". If so, "be" is replaced with "amm"
pattern[n] x for comments with a pattern
pattern[n,m]
s/N.*here\.// escape character
s/N.*?here\.//
s/(?<=i )be/am/;
$string =~ s/x
I\'ve';2
\
substr()
lc() last character of the string
lcfirst()
uc()
ucfirst() concatenation
length() like cut
chop()
chomp vs chop
index()
join()
split(/ /, $string); Portable Operating System Interface [for Unix][1] is the name of a family of related standards specified by the IEEE to define the application programming interface (API), along with shell and utilities interfaces for software compatible with variants of the Unix operating system, although the standard can apply to any operating system.
File Processing using Perl qw returns quoted string '/ / / /'
@ARGV Use library
use POSIX;
use lib qw(/ / /);
use Date::XXX;
$var=$ARGV[0]; For debugging
$var2="$ARGV[0].txt";
open(OUTFILE, ">$var") or die "Can not open output file $var1";
perl -d
Links
http://psoug.org/browse.htm?cid=6
http://www.dwhworld.com/2011/03/perl-script-to-read-a-config-file/
How can Perl split a line on whitespace except when the whitespace is in doublequotes?
http://refcards.com/docs/forda/perl-debugger/perl-debugger-refcard-a4.pdf
http://www.thegeekstuff.com/2010/05/perl-debugger/
http://www.troubleshooters.com/codecorn/littperl/perlreg.htm
Perl Cheat Sheet
http://www.cheat-sheets.org/
Perl Cheat Sheet
http://techcheatsheets.com/tag/perl/
Regular Exp in Perl
Perl Reg Exp Tutorial
Perl Regular Expressions by Example
Perl: Matching using regular expressions
Using Perl, how can I replace all whitespace in a file with newlines?
Trim whitespaces begining and end
Whitespace and perl developers
Perl Regular Expressions
Cheat Sheet and Interview Questions
1. What arguments do you frequently use for the Perl interpreter and what do they mean?
2. What does the command ‘use strict’ do and why should you use it?
3. What do the symbols $ @ and % mean when prefixing a variable?
4. What elements of the Perl language could you use to structure your code to allow for maximum re-use and maximum readability?
5. What are the characteristics of a project that is well suited to Perl?
6. Why do you program in Perl?
7. Explain the difference between my and local.
8. Explain the difference between use and require.
9. What’s your favorite module and why?
10. What is a hash?
11. Write a simple (common) regular expression to match an IP address, e-mail address, city-state-zipcode combination.
12. What purpose does each of the following serve: -w, strict, -T ?
13. What is the difference between for & foreach, exec & system?
14. Where do you go for Perl help? "> $name = ""bam"";
> $$name = 1; # Sets $bam
> ${$name} = 2; # Sets $bam
> ${$name x 2} = 3; # Sets $bambam
> $name->[0] = 4; # Sets $bam[0]
symbolic reference means using a string as a reference."
15. Name an instance where you used a CPAN module. "@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.
-------------------------------------------------------------------------------------------------------------------
Package NewModule;
use Exporter; # an application by ‘use’ operator.#
This Exporter package has @ISA array to look for a specific method this array keeps track of classes it is inheriting.
@ISA qw(Exporter);
@EXPORT qw(VAR1 VAR2 VAR3);
# The symbols VAR1 VAR2 VAR3 loaded by default
@EXPORT_OK qw(VAR4 VAR5);
# the symbols VAR4 and VAR5 only loaded if there is a request."
16. How do you open a file for writing? "use XYZ;
my $objref XYZ->new();"
17. How would you replace a char in string and how do you store the number of replacements? "Explain the difference between ""my"" and ""local"" variable scope declarations. ?
Both of them are used to declare local variables.
The variables declared with ""my"" can live only within the block it was defined and cannot get its visibility inherited functions called within that block, but one defined with ""local"" can live within the block and have its visibility in the functions called within that block.
The variables declared with my() are visible only within the scope of the block which names them. They are not visible outside of this block not even in routines or blocks that it calls. local() variables on the other hand are visible to routines that are called from the block where they are declared. Neither is visible after the end (the final closing curly brace) of the block at all.
Perl supports three scoping declarations that enable to create private variables (using my) selectively global variable (using our) and temporary copies of selected global variables (using local) ... my declares a variable to be scoped within the current block and when the block ends the varaible goes out of scope.. ""local"" is an temporary value to an gobal variable and the value lasts only for the duaration of the block it's just has an temporary value while it's being used within that block...
1) My
My creates a new variable and gives a lexical scope for that variable. The variable is not visible outside the block in which it is defined.
2) Local
Local saves the value of a global variable. It never creates a new variable. Here also the variable is not accessible outside the block but it is visible in the subroutine which is called from the original block. My is more preferring than local . But in various places local is useful where my is illegal
1) Changing the meaning of a special variable like $/
2) Localized file handles
3) Globing"
18. When would you not use Perl for a project? ": s/&zeta1;/ xcexb6 /gthis is working fine in vi.. u want it to rit as a perl code using some match for substitution?see for only some char which are taken as special meaning by perl u have to escape it using ' other wise it will replace nything u want.'
~s/&zeta1;/ xcexb6 /g; is working Fine. If there is any special character use in front of it.......
Then use escape character..
suppose / is the part of string then you can write like / where is escape character
: s/sunil/kartikey/kartikey/sunil/g"
What is the Use of Symbolic Reference in PERL? "Perl is easy fast and its fun to code in perl.
Perl is rich with various packages N/w programming is very easy and there are lot more advantages to say.
Its portable i.e. it can be run Windows / Linux / Solaris and Unix with no changes or with minimum changes.
Unlike othere programming languages Perl has builting support for regex.
just cut down your peice as fast as you can with regex ( If you are master in regex ).
It is having the features of scripting (Shell) as well as programming (like C). Using PERL you can easily do the system administration works where comparitively difficult with Shell script.
* PERL is programmer friendly. It is easy to code and can do it in less number of lines. It does all the nice things with minimum fuzz.
* Text manipulation is unmatched.
* It has built-in regex.
* Has the support of world's largest archive of modules(CPAN)"
"What's the significance of @ISA, @EXPORT @EXPORT_OK
%EXPORT_TAGS list & hashes in a perl package?
With example?" "Refer perldoc. On the command line give perldoc command with various options like e.g.-f function name for function help etc.--Manjusha
I use search.cpan.org or the several Perl books from O'Reily. They are also available online through O'Reily's Safari service and older versions are published as the PERL Bookshelf.
-> perldoc -f function name
Ex: perldoc -f print
perldoc is best help to perl."
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? "Hi
The faviurite module is undoubtly CGI.pmIt simplifies the coding as we no need to worry about the intricacies involving the form processing etc.Thanks Abhishek jain"
Explain the difference between "my" and "local" variable scope declarations. ? CGI DBI etc are very common packages used from CPAN. there are thousands of other useful modules.
"I would like to replace some entities in the text file with symbols using Perl.
This is working fine for some special symbols but for the characters such as Zeta we should use Unicode/Hexadecimal values - xcex96. We are doing like this s/&zeta1;/""xcexb6""/g; . This is working fine only for 2 characters such as xb6. How to use this in Perl? How to make use unicode value for zeta in Perl.
Any kind of help will be appreciated." It provides a GUI
Why do you program in PERL "It is a formatter print it in double quotes to see what I mean.
$^ - Holds the name of the default heading format for the default file handle. Normally it is equal to the file handle's name with _TOP appended to it.
According to the book Perl core language-Little black book $^0 holds the name of the operating system for which the current perl was built.
STDOUT_TOP is the output if we print '$^0 in a console."
Where do you go for perl help? "When:
- There's a lot of text processing
- Web-based applications
- Fast/expidient development
- Shell scripts grow into libraries
- Heavy Data manipulation (auditing accounting checking etc... backend processing)
- Data extraction
- transform
- loading (database etc.)
- System admin etc...
When you are developing an application for a real time system in which processing speed is of utmost importnace"
Whats' your favourite module in PERL and why?
Name an instance you used in CPAN module? package PackageName;
what is a Tk module? WHere it is used? What's the use of it? Plse tell me .. "use POSIX;
use lib qw(/library/perl);
use DBI qw(:sqltypes);
what does this mean '$^0'? tell briefly plse.. $varname="VarCharValue"; OR $varname ="$anotherVar" OR $varname='NumberContant';
when do you not use PERL for a project? $VarName = "$LogDir/FileName.log.".UnixDate(ParseDate("today"), "%m%d"
Defining a package sub { }
Use a library "print ""-----msg----\n"";
Defining a variable and init the same my $varName = "value";
Appending time to log file package::subroutine()
Concatenation operator my $varDate = strftime('%Y-%m-%d %T %Z', localtime);
functions/subroutines $varName = shift(@_);
Print a message printf "[strftime('%Y-%m-%d %T %Z', localtime)] $message\n";
Assigning value to a local variable printf STDERR
Calling a subroutine in a package $#_
Get current time stamp if ($#_ >= 0)
Navigate thru an array time + 3600
Print message with time stamp @Array = localtime $now;
Print on STD ERROR $var = sprintf "%d%02d%02d"
Check no of params $Array[n]
Check if no of params > 0 my $var = new Date::Function(Param=>$var);
Date Time Addition if ($var != "")
Store local time in a array $element->sub();
Print formated time in an array "my $dbh = DBI->connect(""DBI:Oracle:SID"", ""user"", ""pwd"")
die ""Cannot connect to database. "" . DBI->errstr;
my $sql = ""select to_char(to_date(?,'YYYYMMDD'),'YYYYMMDD') from dual"";
my $g = $dbh->prepare($sql)
die ""Cannot prepare query. "" . DBI->errstr;
$g->bind_param(1,$abc, SQL_VARCHAR);
$g->bind_param(2, $id, SQL_INTEGER);
$g->execute
die ""error in shell::execute: $!"";
while ( ($row) = $g->fetchrow_array() )
{
$PortList{$row} = $count;
$count = $count + 1;
}
$g->finish();
return %VarList;"
Refering to nth element in a array sub routineName { return $var }
Call Package Function with Param "while ( ($row) = $g->fetchrow_array() )
{
$count = $count + 1;
$rule = $row;
}"
To check if the variable is blank "open(INDATA, ""$Dir/$FileName"") or die ""Cannot Open Command Pipe $Dir/$FileName"";
open(OUTFILE, "">$Dir/$FileName"") or die ""Cannot open Output file $Dir/FileName"";"
Call a Package subroutine $var == 1
DB Call syntax "sub getValue
{
my $sql = ""select * from table"";
my $g = $dbh->prepare($sql)
die ""Cannot prepare query. "" . DBI->errstr;
$g->execute
die ""error in sth::execute: $!"";
my @dbResult;
while ( (@row) = $g->fetchrow_array() )
{
push(@dbResult, join(',',@row));
}
$g->finish();
return (@dbResult);
};
Subroutine syntax "open(OUTFILE, "">>"" . ""$ARGV[0]"") or die ""Cannot open Output file $ARGV[0]"";
printf OUTFILE ""\n"";
close(OUTFILE);"
While #!/usr/local/bin/perl
Open File Create connection to Oracle Db
Comparison to no system($Path . $script . " " . $file . " >> ". $Log. $yyyymmdd . " 2>&1 &"
Perl to fetch resultset
Add new line charater at the end of the file
First Line
Create connection to Oracle Db
Call a script in Perl
Tutorial Cheat Sheet
Shebang line is the first line starting with #!
Escape charaters
\n new line
\t tab
\r carriage return begin of the current line
\$ end of the current line
\"
\\
\'
\
, = concatenate
printf("Welcome to Perl \n"); = printf "Welcome to Perl \n";
chomp $num1 removes return character at the end
$ scalar variable
$number1 =
Arithmetic Operators
Addition
Operator Precedence (order of evaluation)
*/^ same level left to right for different operators
exponential Right to left
() left to right
+ - last
$c = +7
post and pre increment
$c++
++$c
Associativity of Operators (direction left to right or right to left)
relational operation
== equality = assignment
numeric & string content, and undef example
if add cannot be done no to a string & string cannot be converted into a number then its final result is 0
. Is used for concatenation
Perl Regular Expression
. Evaluates num into string
concatenation . , + tries to conv till cannot
Top10' does not start with no
10Top10' = 20 start with no
Perl is case sensitive
use strict
numeric context undef var = 0
string context undef var = empty
Control Structure
do while vs do until
To compare nos use = < >
To compare strings use eq lt gt
Perl is not a strict data type
ternary operator ? _:_
Arrays & Hashes
Define a array @
Refer individual element $ c[0] $c[1]
Array starts from index 0
@array = { 'sales', 283, "three", 16.439};
Creating and looping
assignment
$array[0] = "Happy";
printf "@array \n"
print "@array \n";
print @array, "\n";
qw operator
@array = qw (this is an array);
print "\n array \n";
@array = {2 .. 5};
$#
$array[$#array]
$# gives last index no gives 9
printf "There are" , scalar(@array), "elements in \@array \n";
gives 10
Negative subscript
$array [-4] 4th element from last
$# array= 4 reduce size to 4
$array = { }; blank out the array
array slices &
@array = qw (zero one two …… nine};
print "@array \n\n";
print "@array[1,3,5,7,9] \n";
{$chiquita , $dole } ={"banana", "pineapple"};
print "\$chiquita = $chiquita \n \$dole=$dole \n";
print "@array \n\n";
{$chiquita, $dole } = {$dole, $chiquita};
print "After swapping values \n";
print "\$chiquita = $chiquita \n \$dole=$dole \n";
push, pop, shift, unshift, functions (stack)
insert extract
begin last
push (@array, $i); push at the end
$elem = pop (@array); push the last element
shift unshift
begin begin
FIFO
1
12
1 2 3
1 2
1
LIFO
1
2 1
3 2 1
2 1
1
Resources : Perl Camel bks
Keywords
undef
? :
qw operator can take array values with spaces
..
push
pop
shift
unshift
scalar
$#
, . +
= eq
= ==
chomp
shebang
\
@array
$array
Splice function
to replace (part of an array)
@replaced = splice (@array , 5, scalar(@array2), @array2);
@removed = splice (@array, 15, 3);
@chopped = splice (@array, 8);
splice (@array);
unless (@array);
{print "\@array has no elements remaining \n"; }
sort array
@reversed = reverse (@array);
@array = {100,23, 9,75,5,10,2,50};
@sorted lexically = sort @array2;
@sortedNumerically = sort {$a < => $b } @array2;
Linear Search / Binary Search
Hash Create and Access hash elements (key value pairs)
%hash ={width =>'300'
height =>'150');
print "\$hash['width'] = $hash['width']\n"
hash are not interpretated when included in " "
print "%hash \n"
print %hash, "\n";
%hash = (one => "I", two => "II")
%hash ={"I", "II")
Using key value each reverse
@keys = keys (% presidents);
while ($key = pop(@key))
{print "$key => $presidents $key} \n";
@values = values(%presidents);
%hash = reverse(%presidents);
each extract key value pairs
while (($key , $value) = each (%presidents));
print "$key => $value \n";
heap = garpage collector
stack = till in scope
Using delete, exists,defined
delete ($hash('Joe')); don’t have to init index increment and terminating condi, perl uses it own index
search any collection
Control Structures
foreach $number ( @array ) manipulations
"foreach $name('Amanda', 'Jeff', 'Sarah')
print ""$name"";
print ""$_"";
print;
all 3 prints the same output"
push (@smallNumbers, $_) if $_ < 6;
@smallNumbers2 = grep( $_ < 6, @numbers) ; continue
push (@doubleNumbers, $_ * 2); goto
@doubledNumbers2 = map( $_ * 2, @numbers); break
foreach ( sort keys (%hash ) ) { print "$_\t", "*" x continue the outer loop without testing
for labels
next exit
next LABEL;
last
redo
"blocks
LABEL: for ( $num = 1; $num <= 10; ++$num ) { next LABLE if ( $num % 2 ==0 ); print ""$num ""; }"
die default scalar variable
subroutines and functions default array
Functions
sub subroutine1 {} shifts arguments
subroutine1 ()
print "$_[$i]"
@_ calling subroutine not defined before use
"displayarguments( ""Sam"", ""Jones"");
sub displayarguments
{
print ""All arguments : @_ \n"";
for
{print ""$_[$i]""}}" not allowed () are required
shift()
for (1 .. 10) { print square ($_), " "; } sub queue { $value = shift(); return $value ** 2; } function to generate a random number
return can return multiple values
&defineBeforeWithoutArguments(); global variable
&defineBeforeWithoutArguments; local, pass by reference
&defineBeforeWithArguments(1,2,3); local, pass by value
rand() packages
srand() eq to import in java, include in c, using c#
our package.variable
my
local
perl modules
require tilt
$main::variable
use strict;
use warnings;
regular expression also returns no of replacements
~ to find digit in the string
if $string =~ m/snow/;
=~ s/world/planet/; digit
same as s(world)(planet); word
s/world/planet/g; white space
/\d/ alpha numeric
/[0-9]/ any non word
\d any non white space
\w and
\s =
\D <>
\W
\S
&&
=~
!~
m/hello
hi there/ 0-1
m/(hello|hi) there/ 1 or more
s/1\d*1/22/; 0 or more
s/1\d+1/22/;
s/1\d?1/22/;
?
+
*
pattern*
pattern+
pattern? first look behind assertion (?<=i ) tests whether the string matched I right before it matched "be". If so, "be" is replaced with "amm"
pattern[n] x for comments with a pattern
pattern[n,m]
s/N.*here\.// escape character
s/N.*?here\.//
s/(?<=i )be/am/;
$string =~ s/x
I\'ve';2
\
substr()
lc() last character of the string
lcfirst()
uc()
ucfirst() concatenation
length() like cut
chop()
chomp vs chop
index()
join()
split(/ /, $string); Portable Operating System Interface [for Unix][1] is the name of a family of related standards specified by the IEEE to define the application programming interface (API), along with shell and utilities interfaces for software compatible with variants of the Unix operating system, although the standard can apply to any operating system.
File Processing using Perl qw returns quoted string '/ / / /'
@ARGV Use library
use POSIX;
use lib qw(/ / /);
use Date::XXX;
$var=$ARGV[0]; For debugging
$var2="$ARGV[0].txt";
open(OUTFILE, ">$var") or die "Can not open output file $var1";
perl -d
Links
http://psoug.org/browse.htm?cid=6
http://www.dwhworld.com/2011/03/perl-script-to-read-a-config-file/
How can Perl split a line on whitespace except when the whitespace is in doublequotes?
http://refcards.com/docs/forda/perl-debugger/perl-debugger-refcard-a4.pdf
http://www.thegeekstuff.com/2010/05/perl-debugger/
http://www.troubleshooters.com/codecorn/littperl/perlreg.htm
No comments:
Post a Comment