Beruflich Dokumente
Kultur Dokumente
‘Hello World’
“Bye World”
3
3.5
-123
0xff (hex)
0377 (octal)
Strings ‘string’
• Interpolation does not take place
• Everything is taken as per it’s face value
• Only exception being ‘\’ character
• Escape special meaning of ‘ with \ => ‘rohit\’s’
Strings “string”
Everything is not taken on it’s face value
Special meaning can be escaped with backslash character
Interpolation: -
$user = “ROHIT”;
print “$user”;
prints ROHIT
print “\$user”;
prints $user
Numerical Literals
42; # The number 42
12.5; # A floating point number
101873.000; # 101,873
.005; # ve thousandths
5E-3; # same number as previous line
23e-100; # 23 times 10 to the power of -100 (very small)
2.3E-99; # The same number as the line above!
23e6; # 23,000,000
23_000_000; # The same number as line above
Data Types
•Scalars
Strings
Single quoted
Double quoted
Numerals
•Arrays
Single Dimensional
Multi Dimensional
•Hashes
Simple Hash
Hash of Hash
More Data Types
References
Scalar Reference: $ScalarRef = \$scalar;
# $$ScalarRef to dereference
Array Reference: $ArrayRef = \@Array;
# @$ArrayRef to dereference
Hash Reference: $HashRef = \%Hash;
# %$HashRef to dereference
• FileHandles
open FILEHANDLE, $filename;
Undefined
Undefined value: $undef = undef;
Typeglobs
*name => ($name, @name, %name,
file-handles,code references,Format templates
Scalars
• Most basic data type
• Stores String and numerical literals
• $scalar_variable_name is preceded by $ symbol
$scalar = “hello”;
$scalar = 123;
$scalar = 10.12;
$scalar = ‘T’;
$scalar = “\n”;
Scalar Semantics
All numerical and string operations supported
$val = 3 # Numerical
Assignment
$sum = 1 + $val; # Sum
$lastname = “Sabharwal”; # String Assignment
$fullname = “Rohit ” . $lastname; #
Concatenation
Type casting during runtime based on operation
Operators
Operators
Numerical Operators
Comparison Operators
Increment-Decrement Operators
String Operator
Assignment Operator
Short-cut Operators
Relational Operators
Numerical Operators
#!c:\perl\bin\perl.exe
print “Enter your age\n”;
$age = <>;
chomp($age);
if($age > 35){
print “You are overage\n”;
}
if-else
if(condition){
statements executed if condition is true;
}
else{
statements executed if condition is false;
}
#!c:\perl\bin\perl.exe
print “Enter your age\n”;
$age = <>;
chomp($age);
if($age > 35){
print “You are overage\n”;
}
else{
print “You are selected\n”;
}
if-elsif-else
if(condition-1){
statements executed if condtion-1 is true;
}
elsif(condition-2){
statements executed if condition-2 is true and condition-1 is false;
}
else{
statements executed if condition-1 and condition-2 are false;
}
if-elsif-else
#!c:\perl\bin\perl.exe
print “Enter your age\n”;
$age = <>;
chomp($age);
if($age > 35){
print “You are overage\n”;
}
elsif($age < 21){
print “You are underage\n”;
}
else{
print “You are selected\n”;
}
unless
unless(condition)
{
statements executed when condition is false;
}
#!c:\perl\bin\perl.exe
print “Enter your age\n”;
$age = <>;
unless($age > 35){
print “You are OK\n”;
}
Control Structures(Iteration)
while
until
do while
do until
for
foreach
while
while(expression){
statements executed till expression is true;
}
$a = 5;
$b = 1;
while($a > $b){
print “$b\n”;
$b++;
}
Until
until(expression){
statements executed till expression is false;
}
$a = 5;
$b = 1;
until($a < $b){
print “$b\n”;
$b++;
}
do-while
do
{
statements to be executed if expression is true;
statements will be executed once after which, expression is checked;
}while(expression)
$a = 5;
$b = 1;
do{
print “$b\n”;
$b++;
}while($a > $b);
do-until
do
{
statements to be executed if expression is false;
statements will be executed once after which, expression is checked;
}until(expression)
$a = 5;
$b = 1;
do{
print “$b\n”;
$b++;
}until($a < $b);
for
for(initialization;expression;increment-or-decrement)
{
statements to be executed till the expression is true;
}
$a =5;
for($i=1;$i<=$a;$i++){
print “$i\n”;
}
foreach
foreach scalar-variable (list)
{
scalar-variable will have value of each element in list, changing
at each iteration;
}
#list can be array or hash
@Arry = (1,2,3,4,5);
foreach $i (@Arry){
print “$i\n”;
}
Next, Last, Redo
LABLE: while (EXPR) {
#redo always comes here and condition is not evaluated
redo LABLE if /:/;
next LABLE if /,/;
last LABLE if /^$/;
do_something;
} continue {
# next always comes here, executes next iteration of loop
do_something_else;
# then back the top to re-check EXPR
}
#last always comes here
Rest of data types
Arrays
List of scalars
Accessed using index
Dynamic memory allocation
Random access to Elements
represented by ‘@’ character in front of array name
push(@Array,’A’,”B”,$C,@D,%E);
unshift(@Array,’A’,”B”,$C,@D,%E);
Modify an element
$Array[0] = ‘B’;
Delete an element
delete($Array[0]);
Array Hash
#Sorting Hash
#Alphabetically or numerically based on keys
@keys = sort { $a cmp or (<=>) $b } (keys %hash);
foreach $key (@keys){
$value = $hash{$key};
print “$key = > $value \n”;
}
#Alphabetically or numerically based on values
foreach $key (sort{$hash{$a} cmp or (<=>) $hash{$b}} keys %hash){
print “$key => $hash{$key}\n”;
}
HASH Excercise
Enter Employee name and age comma separated
Rohit,28,Rahul,30,Guru,40
Operation(Add,Replace,Delete,List)?
Add
Username and age comma separated?
Arjun,50
Arjun aged 50 added
Operation(Add,Replace,Delete,List)?
Replace
Username for replacement
Arjun
Enter new age for Arjun
40
User Arjun’s age changed to 40
Operation(Add,Replace,Delete,List)?
Delete
Username to delete?
Arjun
Arjun deleted
Operation(Add,Replace,Delete,List)?
List
Rohit 28
Rahul30
Guru 40
Operation(Add,Replace,Delete,List)?
File Handling
File Handling
A file is opened using open function
To read
close FILE_HANDLE;
File Handling Example
FOR WRITING FILE
#!/usr/bin/perl
open(FILE, “>test.txt”) or die “Can not create test.txt: $!”;
print FILE “This is a test\n”;
close FILE;
\n Newline
\r Carriage return
\t Tab
\f Formfeed
\s White space character
\S Non-white space character
\w Alphanumeric character a\wb a2b a^b
www.perl.com
www.activestate.com
BACKUP
Reports
Reports
Perl provides FORMAT data-type and format
function for formatting reports
syntax
#To Create
format MYFORMAT =
This is a @<<<<< justified field
“left”
.
#To Write
write MYFORMAT;
Reports
Anchors
@, ^
Auto Repeating Line
~~
Placeholders
Placeholder Alignment Example
< Left Justified @<<<<
> Right Justified @>>>>
| Center Justified @||||
# Numeric @####
* Multiple Line @*
. Floating Point @####.##
% Percentage @##%
Special Variables
Variable Corresponds To
$= The page length
$% The page number
$- The number of lines remaining
$^L The formfeed string
Report Example
@employee = ("Rohit", "Naveen", "Abhinav", "Rajeev");
@salary = (1000, 2000, 3000, 4000);
format STDOUT_TOP =
@|||||||||||||||||||||||
"Employee Salary Report";
------------------------
@<<<<<<<<<< @<<<<<<<
"NAME", "SALARY";
------------------------
.
for($i=0;$i<=3;$i++)
{
format STDOUT =
@<<<<<<<<<< @####.##
$employee[$i], $salary[$i];
.
write;
}
print "------------------------\n";
$footer = "\nEnd Page $%\n";
print $footer;
Reports — Script Output
End Page 1
Debugging
Errors & Warnings
Catch $!
Use warn or die
Catch $^E to get OS reported errors
Use eval{} block to catch $@
use Fatal qw(open close sysopen);
use POSIX qw(:errno_h);
use Carp, crap, croak, cluck, confess
use Sys::Syslog;
use Win32::Eventlog;
Debugging
Compile perl with –DDEBUG option
use debug flags(Next slide)
use ‘print’ or own debug routines
Example:- Profiling a script
perl –d:DProf script.pl
dprofpp
OUTPUT
Total Elapsed Time = -0.00034 Seconds
User+System Time = 0.129317 Seconds
Exclusive Times
%Time ExclSec CumulS #Calls sec/call Csec/c Name
46.4 0.060 0.120 2 0.0300 0.0599 main::BEGIN
15.4 0.020 0.020 1 0.0200 0.0200 vars::BEGIN
Debugging
This shows the debug flags, which can be specified with the -D command-line option. If you specify a
number, you can simply add all the numbers of each flag together so that 6 is 4 and 2. If you use the letter as a
flag then simply list all the options required. The following two calls are equivalent:
#perl -d -Dls test.pl
#perl -d -D6 test.pl Perl Debugging Flags
Flag Number Flag Letter Meaning of Flag
1 p Tokenizing and parsing
2 s Stack snapshots
4 l Label stack processing
8 t Trace execution
16 o Operator node construction
32 c String/numeric conversions
64 P Print preprocessor command for -P
128 m Memory allocation
256 f Format processing
512 r Regular expression parsing
1024 x Syntax tree dump
2048 u Tainting checks
4096 L Memory leaks (not supported anymore)
8192 H Hash dump; usurps values()
6384 X Scratchpad allocation (Perl 5 only)
32768 D Cleaning up (Perl 5 only)
Subroutine Recursion
One the most powerful features of subroutines is their ability to call
themselves. There are many problems that can be solved by repeated
application of the same procedure. However, care must be taken to set up
a termination condition where the recursion stops and the execution can
unravel itself. Example is the calculation of a factorial value:
#!/usr/bin/perl -w
# # Example factorial using recursion
for ($x=1; $x<100; $x++) {
print "Factorial $x is ",&factorial($x), "\n";
}
sub factorial {
local($x) = @_;
if ($x == 1) {
return 1;
}
else {
return ($x*($x-1) + &factorial($x-1));
}
}
Perl Command Line Switches
Usage: C:\Perl\bin\Perl.exe [switches] [--] [program-file]
[arguments]
-0[octal] specify record separator (\0, if no argument)
-a autosplit mode with -n or -p (splits $_ into @F)
-C enable native wide character system interfaces
-c check syntax only (runs BEGIN and CHECK blocks)
-d[:debugger] run program under debugger
-D[number/list] set debugging flags (argument is a bit mask
or alphabets)
-e 'command' one line of program (several -e's allowed,
omit program file)
-F/pattern/ split() pattern for -a switch (//'s are optional)
-i[extension] edit <> files in place (makes backup if
extension supplied)
Perl Command Line Switches
-Idirectory specify @INC/#include directory (several -I's allowed)
-l[octal] enable line ending processing, specifies line terminator
-[mM][-]module execute `use/no module...' before executing program
-n assume 'while (<>) { ... }' loop around program
-p assume loop like -n but print line also, like sed
-P run program through C preprocessor before compilation
-s enable rudimentary parsing for switches after programfile
-S look for programfile using PATH environment variable
-T enable tainting checks
-u dump core after parsing program
-U allow unsafe operations
-v print version, subversion (includes VERY IMPORTANT perl info)
-V[:variable] print configuration summary (or a single Config.pm variable)
-w enable many useful warnings (RECOMMENDED)
-W enable all warnings
-X disable all warnings
-x[directory] strip off text before #!perl line and perhaps cd to directory
Perl Command Line Execution
The -e option is handy for quick Perl operations from the command line.
Want to change all instances of "oldstring" in Wiffle.bat to "newstring"?
Try
perl -i.old -p -e "s/ oldstring/ newstring/g" wiffle.bat
This says: "Take each line of Wiffle.bat (-p); store the original in
Wiffle.old (-i); substitute all instances of oldstring with newstring (-e);
write the result (-p) to the original file (-i)."
perl -e 's/gopher/http/gi' -p -i.bak *.html
Changing ‘gopher’ to ‘http’ in multiple files
Predefined Variables
$! #Keeps Last Error or Exception
$@ #Array of string indicating source of last exception
$& #Last Successful pattern match in scope
$` #String Preceding whatever was matched
$‘ #String Proceeding whatever was matched
$+ #Last bracket that was matched
$1, $2..# Matched Elements
$~ #Last match in current scope
$. #Current line number of the last file read
$_ #Last input line of string
$0 #Name of perl script that is being executed
$* #Command line arguments given for the script
$$ #The process number of running script
$? #Status of the executed child process
$],$^V #Perl Version
Special Characters
\\ => An actual, single backslash character
\$ => A single $ character
\@ => A single @ character
\t => Tab
\n => Newline
\r => Hard return
\f => Form feed
\b => Backspace
\a => Alarm (bell)
\e => Escape
\033 => Character represented by octal value, 033
\x1b => Character represented by hexadecimal value, 1b
Some RegEx examples
# convert to UPPERCASE
# returns $line = $line (all in uppercase)
$line =~ tr/a-z/A-Z/;
# convert to lowercase
# returns $line = $line (all in lowercase)
$line =~ tr/A-Z/a-z/;
# remove leading whitespace
# returns $line with no leading whitespace
$line =~ s/^\s+//;
# remove trailing whitespace
# returns $line with no trailing whitespace
# note: this will also remove \n
$line =~ s/\s+$//
Some RegEx examples contd
# check for Y2K date (4-digit year specified)
# format exactly: nn/nn/nnnn or nn-nn-nnnn
# returns true if proper format
($line1 =~ m/[0-9]{2}[\/|-][0-9]{2}[\/|-][0-9]{4}/)
# find word that is bolded
# returns: $1 = 'text‘
$line = "This is some <b>text</b> with HTML <tags> and ";
$line =~ m/<b>(.*)<\/b>/i;
# convert <STRONG> to <B>
$line =~ s/<(\/?)strong>/<$1b>/gi;
# strip HTML tags (not the best way)
# returns $line = 'This is some with HTML and words'
$line = "This is some <b>text</b> with HTML <tags> and words";
$line =~ s/<(.*?)>//gi;
The Bit-Wise Operators