SlideShare a Scribd company logo
1 of 60
Lecture 7: Perl Introduction
Programming Tools and
Environments
Perl
"Practical Extraction and Reporting Language"
written by Larry Wall and first released in 1987
Perl has become a very large system of
modules
name came first, then the acronym
designed to be a "glue" language to fill the gap
between compiled programs (output of "gcc",
etc.) and scripting languages
"Perl is a language for easily manipulating text,
files and processes": originally aimed at
systems administrators and developers
What is Perl?
Perl is a High-level Scripting language
Faster than sh or csh, slower than C
No need for sed, awk, head, wc, tr, …
Compiles at run-time
Available for Unix, PC, Mac
Best Regular Expressions on Earth
What’s Perl Good For?
Quick scripts, complex scripts
Parsing & restructuring data files
CGI-BIN scripts
High-level programming
 Networking libraries
 Graphics libraries
 Database interface libraries
What’s Perl Bad For?
Compute-intensive applications (use C)
Hardware interfacing (device drivers…)
Executing Perl scripts
"bang path" convention for scripts:
 can invoke Perl at the command line, or
 add #!/public/bin/perl at the beginning of the script
 exact value of path depends upon your platform (use
"which perl" to find the path)
one execution method:
% perl
print "Hello, World!n";
CTRL-D
Hello, World!
preferred method: set bang-path and ensure
executable flag is set on the script file
Perl Basics
Comment lines begin with: #
File Naming Scheme
 filename.pl (programs)
 filename.pm (modules)
Example prog: print “Hello, World!n”;
Perl Basics
Statements must end with semicolon
 $a = 0;
Should call exit() function when finished
 Exit value of zero means success
 exit (0); # successful
 Exit value non-zero means failure
 exit (2); # failure
Data Types
Integer
 25 750000 1_000_000_000
 8#100 16#FFFF0000
Floating Point
 1.25 50.0 6.02e23 -1.6E-8
String
 ‘hi there’ “hi there, $name” qq(tin can)
 print “Text Utility, version $vern”;
Data Types
Boolean
 0 0.0 “” "0" represent False
 all other values represent True
Variable Types
Scalar
 $num = 14;
 $fullname = “John H. Smith”;
 Variable Names are Case Sensitive
 Underlines Allowed: $Program_Version = 1.0;
Scalars
usage of scalars:
print ("pi is equal to: $pin");
print "pi is still equal to: ", $pi, "n";
$c = $a + $b
important! A scalar variable can be "used" before it is
first assigned a value
 result depends on context
 either a blank string ("") or a zero (0)
 this is a source of very subtle bugs
 if variable name is mispelled — what should be the
result?
 do not let yourself get caught by this – use the "-w"
flag in the bang path:
#!/public/bin/perl -w
Variable Types
List (one-dimensional array)
 @memory = (16, 32, 48, 64);
 @people = (“Alice”, “Alex”, “Albert”);
 First element numbered 0
 Single elements are scalar: $names[0] = “Fred”;
 Slices are ranges of elements
 @guys = @people[1..2];
 How big is my list?
 print “Number of people: “, scalar @people, “ n”;
Variable Types
Hash (associative array)
 %var = { “name” => “paul”, “age” => 33
};
 Single elements are scalar
 print $var{“name”}; $var{age}++;
 How many elements are in my hash?
 @allkeys = keys(%var);
 $num = @allkeys;
Operators
Math
 The usual suspects: + - * / %
 $total = $subtotal * (1 + $tax / 100.0);
 Exponentiation: **
 $cube = $value ** 3;
 $cuberoot = $value ** (1.0/3);
 Bit-level Operations
 left-shift: << $val = $bits << 1;
 right-shift: >> $val = $bits >> 8;
Operators
Assignments
 As usual: = += -= *= /= **= <<=
>>=
 $value *= 5;
 $longword <<= 16;
 Increment: ++
 $counter++ ++$counter
 Decrement: --
 $num_tries-- --$num_tries
Arithmetic
Perl operators are the same as in C and Java
these are only good for numbers
 but beware:
$b = "3" + "5";
print $b, "n"; # prints the number 8
 if a string can be interpreted as a number given
arithmetic operators, it will be
 what is the value of $b?:
$b = "3" + "five" + 6?
 Perl semantics can be tricky to completely understand
Operators
Boolean (against bits in each byte)
 Usual operators: & |
 Exclusive-or:^
 Bitwise Negation: ~
 $picture = $backgnd & ~$mask | $image;
Boolean Assignment
 &= |= ^=
 $picture &= $mask;
Operators
Logical (expressions)
 && And operator
 | | Or operator
 ! Not operator
Operators
 Short Circuit Operators
 expr1 && expr2
 expr1 is evaluated.
 expr2 is only evaluated if expr1 was true.
 expr1 || expr2
 expr1 is evaluated.
 expr2 is only evaluated if expr1 was false.
 Examples
 open (…) || die “couldn’t open file”;
 $debug && print “user’s name is $namen”;
Operators
Modulo: %
 $a = 123 % 10; ($a is 3)
Multiplier: x
 print “ride on the ”, “choo-”x2, “train”;
(prints “ride on the choo-choo-train”)
 $stars = “*” x 80;
Assignment: %= x=
Operators
String Concatenation: . .=
 $name = “Uncle” . $space . “Sam”;
 $cost = 34.99;
 $price = “Hope Diamond, now only $”;
 $price .= “$cost”;
Conditionals
numeric string
Equal: == eq
Less/Greater Than: < > lt gt
Less/Greater or equal: <= >= le ge
Zero and empty-string means False
All other values equate to True
Conditionals
numeric string
Comparison: <=> cmp
 Results in a value of -1, 0, or 1
Logical Not: !
 if (! $done) {
print “keep going”;
}
numeric vs. string comparisons
#!/usr/bin/perl
$a = "123";
$b = "1234";
$c = "124";
if ($b > $c) {
print "$b > $cn";
} else {
print "$b <= $cn";
}
if ($b gt $c) {
print "$b gt $cn";
} else {
print "$b le $cn";
}
1234 > 124
1234 le 124
Control Structures
“if” statement - first style
 if ($porridge_temp < 40) {
print “too hot.n”;
}
elsif ($porridge_temp > 150) {
print “too cold.n”;
}
else {
print “just rightn”;
}
Control Structures
“if” statement - second style
 statement if condition;
 print “$index is $index” if $DEBUG;
 Single statements only
 Simple expressions only
“unless” is a reverse “if”
 statement unless condition;
 print “millenium is here!” unless $year < 2000;
Control Structures
“for” loop - first style
 for (initial; condition; increment) { code }
 for ($i=0; $i<10; $i++) {
print “hellon”;
}
“for” loop - second style
 for [variable] (range) { code }
 for $name (@employees) {
print “$name is an employee.n”;
}
Control Structures
“for” loop with default loop variable
 for (@employees) {
print “$_ is an employeen”;
print; # this prints “$_”
}
Foreach and For are actually the same.
Control Structures
“while” loop
 while (condition) { code }
 $cars = 7;
while ($cars > 0) {
print “cars left: ”, $cars--, “n”;
}
 while ($game_not_over) {…}
Control Structures
“until” loop is opposite of “while”
 until (condition) { code }
 $cars = 7;
until ($cars <= 0) {
print “cars left: ”, $cars--, “n”;
}
 while ($game_not_over) {…}
Control Structures
Bottom-check Loops
 do { code } while (condition);
 do { code } until (condition);
 $value = 0;
do {
print “Enter Value: ”;
$value = <STDIN>;
} until ($value > 0);
No Switch Statement?!?
Perl needs no Switch (Case) statement.
Use if/else combinations instead
 if (cond1) { … }
elsif (cond2) { … }
elsif…
else…
This will be optimized at compile time
Subroutines (Functions)
Defining a Subroutine
 sub name { code }
 Arguments passed in via “@_” list
 sub multiply {
my ($a, $b) = @_;
return $a * $b;
}
 Last value processed is the return value
(could have left out word “return”, above)
Subroutines (Functions)
Calling a Subroutine
 &subname; # no args, no return value
 &subname (args);
 retval = &subname (args);
 The “&” is optional so long as…
 subname is not a reserved word
 subroutine was defined before being called
Subroutines (Functions)
Passing Arguments
 Passes the value
 Lists are expanded
 @a = (5,10,15);
@b = (20,25);
&mysub(@a,@b);
 this passes five arguments: 5,10,15,20,25
 mysub can receive them as 5 scalars, or one array
Subroutines (Functions)
Examples
 sub good1 {
my($a,$b,$c) = @_;
}
&good1 (@triplet);
 sub good2 {
my(@a) = @_;
}
&good2 ($one, $two, $three);
Subroutines (Functions)
Examples
 sub good3 {
my($a,$b,@c) = @_;
}
&good3 ($name, $phone, @address);
 sub bad1 {
my(@a,$b) = @_;
}
 @a will absorb all args, $b will have nothing.
Dealing with Hashes
keys( ) - get an array of all keys
 foreach (keys (%hash)) { … }
values( ) - get an array of all values
 @array = values (%hash);
each( ) - get key/value pairs
 while (@pair = each(%hash)) {
print “element $pair[0] has $pair[1]n”;
}
Dealing with Hashes
exists( ) - check if element exists
 if (exists $ARRAY{$key}) { … }
delete( ) - delete one element
 delete $ARRAY{$key};
Launching External Programs
The “system” library call
 example: system (“ls -la”);
 Returns exit status of program it launched
 a shell actually runs, so you can use:
 pipes (“|”)
 redirection (“<”, “>”)
Launching External Programs
Run a command, insert output inline
 $numlines = `wc -l < /etc/passwd`;
Command Line Args
$0 = program name
@ARGV array of arguments to program
zero-based index (default for all arrays)
Example
 yourprog -a somefile
 $0 is “yourprog”
 $ARGV[0] is “-a”
 $ARGV[1] is “somefile”
Basic File I/O
Reading a File
 open (FILEHANDLE, “$filename”) || die 
“open of $filename failed: $!”;
while (<FILEHANDLE>) {
chomp $_; # or just: chomp;
print “$_n”;
}
close FILEHANDLE;
Basic File I/O
Writing a File
 open (FILEHANDLE, “>$filename”) || die 
“open of $filename failed: $!”;
while (@data) {
print FILEHANDLE “$_n”;
# note, no comma!
}
close FILEHANDLE;
Basic File I/O
Predefined File Handles
 <STDIN> input
 <STDOUT> output
 <STDERR> output
 print STDERR “big bad error occurredn”;
 <> ARGV or STDIN
Basic File I/O
How does <> work?
 opens each ARGV filename for reading
 if no ARGV’s, reads from stdin
 great for writing filters, here’s “cat”:
 while (<>) {
print; # same as print “$_”;
}
Basic File I/O
Reading from a Pipe
 open (FILEHANDLE, “ps aux |”) || die 
“launch of ‘ps’ failed: $!”;
while (<FILEHANDLE>) {
chomp;
print “$_n”;
}
close FILEHANDLE;
Basic File I/O
Writing to a Pipe
 open (FILEHANDLE, “| mail frank”) || die 
“launch of ‘mail’ failed: $!”;
while (@data) {
print FILEHANDLE “$_n”;
}
close FILEHANDLE;
Common mistakes
putting comma after filehandle in print statement
using == instead of eq, and != instead of ne
leaving $ off the front of a variable on th left side of
an assignment
forgetting the & on a subroutine call
leaving $ off of the loop variable of foreach
using else if or elif instead of elsif
forgetting trailing semicolon
forgetting the @ or @ on the front of variables
saying @foo[1] when you mean $foo[1]
Debugging in Perl
-w option is great!
 #!/bin/perl -w
 tells you about…
 misused variables
 using uninitialized data/varables
 identifiers that are used only once
 and more
Debugging in Perl
Debug mode: perl -d filename [args]
 Display Commands
 h Extended help
 h h Abbreviated help
 l (lowercase-L) list lines of code
 l sub list subroutine sub
 l 5 list line 5
 l 3-6 list lines 3 through 6 inclusive
 l list next window of lines
Debugging in Perl
 Display Commands (continued)
 w list window around current location
 S list all subroutines w/ packages
 V [pkg] list all variables [in package pkg]
 X [vars] list variables in this package
 /pat search forwards for pattern pat
(regular expressions legal)
 ?pat search backwards for pattern pat
(regular expressions legal)
Debugging in Perl
 Display Commands (continued)
 - (hyphen) list previous window
 p expr prints Perl expression expr
 = alias value set a command alias
 H [-num] history (list previous cmds)
 !num redo a debug
command
 command execute any Perl command
or line of code you want
 q quit
Debugging in Perl
 Stepping & Tracing
 s step -- execute 1 line of code.
Steps “over” subroutines.
 n next -- execute 1 line of code.
Steps “into” subroutines.
 [RETURN] repeats previous “step” or “next”
 r return from function
 t toggle trace mode
Debugging in Perl
 Breakpoints
 b line set a breakpoint at line line
 b sub set a breakpoint at subroutine sub
 d line delete breakpoint
 D delete all breakpoints
 c [line] continue running until next breakpt
[set a temporary breakpoint at line]
 L List all breakpoints
Debugging in Perl
 Actions
 a line cmd executes perl code cmd
each time line is reached
 A delete all line actions
 < cmd set action right before the
debugging prompt
 > cmd set action right after the
debugging prompt
Debugging in Perl
How to Learn More
 man perldebug
 just try it!
CPAN
Comprehensive Perl Archive Network
 Hundreds of reusable Perl modules written
by people on the Internet
 Archive sites
 ftp://ftp.cs.colorado.edu/pub/perl/CPAN/
 ftp://ftp.cdrom.com/pub/perl/CPAN/
 ftp://ftp.orst.edu/pub/packages/CPAN/
How to Learn More
 On-line man pages
 man perl -- starting point
man perldoc -- documentation
man perlmod -- modules
 perldoc command gives manpage-like info
 example: perldoc Getopt::Std

More Related Content

Similar to Introduction to Perl

Similar to Introduction to Perl (20)

Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
Perl Intro 4 Debugger
Perl Intro 4 DebuggerPerl Intro 4 Debugger
Perl Intro 4 Debugger
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Learning Perl 6
Learning Perl 6 Learning Perl 6
Learning Perl 6
 
Lecture 22
Lecture 22Lecture 22
Lecture 22
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
 
Cleancode
CleancodeCleancode
Cleancode
 
Perl courseparti
Perl coursepartiPerl courseparti
Perl courseparti
 
Php & my sql
Php & my sqlPhp & my sql
Php & my sql
 
Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)
 
Perl Basics with Examples
Perl Basics with ExamplesPerl Basics with Examples
Perl Basics with Examples
 
Web Technology_10.ppt
Web Technology_10.pptWeb Technology_10.ppt
Web Technology_10.ppt
 
PHP and MySQL
PHP and MySQLPHP and MySQL
PHP and MySQL
 
Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)
 
Beginning Perl
Beginning PerlBeginning Perl
Beginning Perl
 
PHP_Lecture.pdf
PHP_Lecture.pdfPHP_Lecture.pdf
PHP_Lecture.pdf
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Perl Introduction
Perl IntroductionPerl Introduction
Perl Introduction
 
PHP-01-Overview.ppt
PHP-01-Overview.pptPHP-01-Overview.ppt
PHP-01-Overview.ppt
 

More from NBACriteria2SICET

More from NBACriteria2SICET (7)

Basics of Classification.ppt
Basics of Classification.pptBasics of Classification.ppt
Basics of Classification.ppt
 
PHP InterLevel.ppt
PHP InterLevel.pptPHP InterLevel.ppt
PHP InterLevel.ppt
 
Support Vector Machine.ppt
Support Vector Machine.pptSupport Vector Machine.ppt
Support Vector Machine.ppt
 
Collision in Hashing.pptx
Collision in Hashing.pptxCollision in Hashing.pptx
Collision in Hashing.pptx
 
Mining Frequent Itemsets.ppt
Mining Frequent Itemsets.pptMining Frequent Itemsets.ppt
Mining Frequent Itemsets.ppt
 
Linked List.ppt
Linked List.pptLinked List.ppt
Linked List.ppt
 
Preprocessing.ppt
Preprocessing.pptPreprocessing.ppt
Preprocessing.ppt
 

Recently uploaded

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 

Recently uploaded (20)

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 

Introduction to Perl

  • 1. Lecture 7: Perl Introduction Programming Tools and Environments
  • 2. Perl "Practical Extraction and Reporting Language" written by Larry Wall and first released in 1987 Perl has become a very large system of modules name came first, then the acronym designed to be a "glue" language to fill the gap between compiled programs (output of "gcc", etc.) and scripting languages "Perl is a language for easily manipulating text, files and processes": originally aimed at systems administrators and developers
  • 3. What is Perl? Perl is a High-level Scripting language Faster than sh or csh, slower than C No need for sed, awk, head, wc, tr, … Compiles at run-time Available for Unix, PC, Mac Best Regular Expressions on Earth
  • 4. What’s Perl Good For? Quick scripts, complex scripts Parsing & restructuring data files CGI-BIN scripts High-level programming  Networking libraries  Graphics libraries  Database interface libraries
  • 5. What’s Perl Bad For? Compute-intensive applications (use C) Hardware interfacing (device drivers…)
  • 6. Executing Perl scripts "bang path" convention for scripts:  can invoke Perl at the command line, or  add #!/public/bin/perl at the beginning of the script  exact value of path depends upon your platform (use "which perl" to find the path) one execution method: % perl print "Hello, World!n"; CTRL-D Hello, World! preferred method: set bang-path and ensure executable flag is set on the script file
  • 7. Perl Basics Comment lines begin with: # File Naming Scheme  filename.pl (programs)  filename.pm (modules) Example prog: print “Hello, World!n”;
  • 8. Perl Basics Statements must end with semicolon  $a = 0; Should call exit() function when finished  Exit value of zero means success  exit (0); # successful  Exit value non-zero means failure  exit (2); # failure
  • 9. Data Types Integer  25 750000 1_000_000_000  8#100 16#FFFF0000 Floating Point  1.25 50.0 6.02e23 -1.6E-8 String  ‘hi there’ “hi there, $name” qq(tin can)  print “Text Utility, version $vern”;
  • 10. Data Types Boolean  0 0.0 “” "0" represent False  all other values represent True
  • 11. Variable Types Scalar  $num = 14;  $fullname = “John H. Smith”;  Variable Names are Case Sensitive  Underlines Allowed: $Program_Version = 1.0;
  • 12. Scalars usage of scalars: print ("pi is equal to: $pin"); print "pi is still equal to: ", $pi, "n"; $c = $a + $b important! A scalar variable can be "used" before it is first assigned a value  result depends on context  either a blank string ("") or a zero (0)  this is a source of very subtle bugs  if variable name is mispelled — what should be the result?  do not let yourself get caught by this – use the "-w" flag in the bang path: #!/public/bin/perl -w
  • 13. Variable Types List (one-dimensional array)  @memory = (16, 32, 48, 64);  @people = (“Alice”, “Alex”, “Albert”);  First element numbered 0  Single elements are scalar: $names[0] = “Fred”;  Slices are ranges of elements  @guys = @people[1..2];  How big is my list?  print “Number of people: “, scalar @people, “ n”;
  • 14. Variable Types Hash (associative array)  %var = { “name” => “paul”, “age” => 33 };  Single elements are scalar  print $var{“name”}; $var{age}++;  How many elements are in my hash?  @allkeys = keys(%var);  $num = @allkeys;
  • 15. Operators Math  The usual suspects: + - * / %  $total = $subtotal * (1 + $tax / 100.0);  Exponentiation: **  $cube = $value ** 3;  $cuberoot = $value ** (1.0/3);  Bit-level Operations  left-shift: << $val = $bits << 1;  right-shift: >> $val = $bits >> 8;
  • 16. Operators Assignments  As usual: = += -= *= /= **= <<= >>=  $value *= 5;  $longword <<= 16;  Increment: ++  $counter++ ++$counter  Decrement: --  $num_tries-- --$num_tries
  • 17. Arithmetic Perl operators are the same as in C and Java these are only good for numbers  but beware: $b = "3" + "5"; print $b, "n"; # prints the number 8  if a string can be interpreted as a number given arithmetic operators, it will be  what is the value of $b?: $b = "3" + "five" + 6?  Perl semantics can be tricky to completely understand
  • 18. Operators Boolean (against bits in each byte)  Usual operators: & |  Exclusive-or:^  Bitwise Negation: ~  $picture = $backgnd & ~$mask | $image; Boolean Assignment  &= |= ^=  $picture &= $mask;
  • 19. Operators Logical (expressions)  && And operator  | | Or operator  ! Not operator
  • 20. Operators  Short Circuit Operators  expr1 && expr2  expr1 is evaluated.  expr2 is only evaluated if expr1 was true.  expr1 || expr2  expr1 is evaluated.  expr2 is only evaluated if expr1 was false.  Examples  open (…) || die “couldn’t open file”;  $debug && print “user’s name is $namen”;
  • 21. Operators Modulo: %  $a = 123 % 10; ($a is 3) Multiplier: x  print “ride on the ”, “choo-”x2, “train”; (prints “ride on the choo-choo-train”)  $stars = “*” x 80; Assignment: %= x=
  • 22. Operators String Concatenation: . .=  $name = “Uncle” . $space . “Sam”;  $cost = 34.99;  $price = “Hope Diamond, now only $”;  $price .= “$cost”;
  • 23. Conditionals numeric string Equal: == eq Less/Greater Than: < > lt gt Less/Greater or equal: <= >= le ge Zero and empty-string means False All other values equate to True
  • 24. Conditionals numeric string Comparison: <=> cmp  Results in a value of -1, 0, or 1 Logical Not: !  if (! $done) { print “keep going”; }
  • 25. numeric vs. string comparisons #!/usr/bin/perl $a = "123"; $b = "1234"; $c = "124"; if ($b > $c) { print "$b > $cn"; } else { print "$b <= $cn"; } if ($b gt $c) { print "$b gt $cn"; } else { print "$b le $cn"; } 1234 > 124 1234 le 124
  • 26. Control Structures “if” statement - first style  if ($porridge_temp < 40) { print “too hot.n”; } elsif ($porridge_temp > 150) { print “too cold.n”; } else { print “just rightn”; }
  • 27. Control Structures “if” statement - second style  statement if condition;  print “$index is $index” if $DEBUG;  Single statements only  Simple expressions only “unless” is a reverse “if”  statement unless condition;  print “millenium is here!” unless $year < 2000;
  • 28. Control Structures “for” loop - first style  for (initial; condition; increment) { code }  for ($i=0; $i<10; $i++) { print “hellon”; } “for” loop - second style  for [variable] (range) { code }  for $name (@employees) { print “$name is an employee.n”; }
  • 29. Control Structures “for” loop with default loop variable  for (@employees) { print “$_ is an employeen”; print; # this prints “$_” } Foreach and For are actually the same.
  • 30. Control Structures “while” loop  while (condition) { code }  $cars = 7; while ($cars > 0) { print “cars left: ”, $cars--, “n”; }  while ($game_not_over) {…}
  • 31. Control Structures “until” loop is opposite of “while”  until (condition) { code }  $cars = 7; until ($cars <= 0) { print “cars left: ”, $cars--, “n”; }  while ($game_not_over) {…}
  • 32. Control Structures Bottom-check Loops  do { code } while (condition);  do { code } until (condition);  $value = 0; do { print “Enter Value: ”; $value = <STDIN>; } until ($value > 0);
  • 33. No Switch Statement?!? Perl needs no Switch (Case) statement. Use if/else combinations instead  if (cond1) { … } elsif (cond2) { … } elsif… else… This will be optimized at compile time
  • 34. Subroutines (Functions) Defining a Subroutine  sub name { code }  Arguments passed in via “@_” list  sub multiply { my ($a, $b) = @_; return $a * $b; }  Last value processed is the return value (could have left out word “return”, above)
  • 35. Subroutines (Functions) Calling a Subroutine  &subname; # no args, no return value  &subname (args);  retval = &subname (args);  The “&” is optional so long as…  subname is not a reserved word  subroutine was defined before being called
  • 36. Subroutines (Functions) Passing Arguments  Passes the value  Lists are expanded  @a = (5,10,15); @b = (20,25); &mysub(@a,@b);  this passes five arguments: 5,10,15,20,25  mysub can receive them as 5 scalars, or one array
  • 37. Subroutines (Functions) Examples  sub good1 { my($a,$b,$c) = @_; } &good1 (@triplet);  sub good2 { my(@a) = @_; } &good2 ($one, $two, $three);
  • 38. Subroutines (Functions) Examples  sub good3 { my($a,$b,@c) = @_; } &good3 ($name, $phone, @address);  sub bad1 { my(@a,$b) = @_; }  @a will absorb all args, $b will have nothing.
  • 39. Dealing with Hashes keys( ) - get an array of all keys  foreach (keys (%hash)) { … } values( ) - get an array of all values  @array = values (%hash); each( ) - get key/value pairs  while (@pair = each(%hash)) { print “element $pair[0] has $pair[1]n”; }
  • 40. Dealing with Hashes exists( ) - check if element exists  if (exists $ARRAY{$key}) { … } delete( ) - delete one element  delete $ARRAY{$key};
  • 41. Launching External Programs The “system” library call  example: system (“ls -la”);  Returns exit status of program it launched  a shell actually runs, so you can use:  pipes (“|”)  redirection (“<”, “>”)
  • 42. Launching External Programs Run a command, insert output inline  $numlines = `wc -l < /etc/passwd`;
  • 43. Command Line Args $0 = program name @ARGV array of arguments to program zero-based index (default for all arrays) Example  yourprog -a somefile  $0 is “yourprog”  $ARGV[0] is “-a”  $ARGV[1] is “somefile”
  • 44. Basic File I/O Reading a File  open (FILEHANDLE, “$filename”) || die “open of $filename failed: $!”; while (<FILEHANDLE>) { chomp $_; # or just: chomp; print “$_n”; } close FILEHANDLE;
  • 45. Basic File I/O Writing a File  open (FILEHANDLE, “>$filename”) || die “open of $filename failed: $!”; while (@data) { print FILEHANDLE “$_n”; # note, no comma! } close FILEHANDLE;
  • 46. Basic File I/O Predefined File Handles  <STDIN> input  <STDOUT> output  <STDERR> output  print STDERR “big bad error occurredn”;  <> ARGV or STDIN
  • 47. Basic File I/O How does <> work?  opens each ARGV filename for reading  if no ARGV’s, reads from stdin  great for writing filters, here’s “cat”:  while (<>) { print; # same as print “$_”; }
  • 48. Basic File I/O Reading from a Pipe  open (FILEHANDLE, “ps aux |”) || die “launch of ‘ps’ failed: $!”; while (<FILEHANDLE>) { chomp; print “$_n”; } close FILEHANDLE;
  • 49. Basic File I/O Writing to a Pipe  open (FILEHANDLE, “| mail frank”) || die “launch of ‘mail’ failed: $!”; while (@data) { print FILEHANDLE “$_n”; } close FILEHANDLE;
  • 50. Common mistakes putting comma after filehandle in print statement using == instead of eq, and != instead of ne leaving $ off the front of a variable on th left side of an assignment forgetting the & on a subroutine call leaving $ off of the loop variable of foreach using else if or elif instead of elsif forgetting trailing semicolon forgetting the @ or @ on the front of variables saying @foo[1] when you mean $foo[1]
  • 51. Debugging in Perl -w option is great!  #!/bin/perl -w  tells you about…  misused variables  using uninitialized data/varables  identifiers that are used only once  and more
  • 52. Debugging in Perl Debug mode: perl -d filename [args]  Display Commands  h Extended help  h h Abbreviated help  l (lowercase-L) list lines of code  l sub list subroutine sub  l 5 list line 5  l 3-6 list lines 3 through 6 inclusive  l list next window of lines
  • 53. Debugging in Perl  Display Commands (continued)  w list window around current location  S list all subroutines w/ packages  V [pkg] list all variables [in package pkg]  X [vars] list variables in this package  /pat search forwards for pattern pat (regular expressions legal)  ?pat search backwards for pattern pat (regular expressions legal)
  • 54. Debugging in Perl  Display Commands (continued)  - (hyphen) list previous window  p expr prints Perl expression expr  = alias value set a command alias  H [-num] history (list previous cmds)  !num redo a debug command  command execute any Perl command or line of code you want  q quit
  • 55. Debugging in Perl  Stepping & Tracing  s step -- execute 1 line of code. Steps “over” subroutines.  n next -- execute 1 line of code. Steps “into” subroutines.  [RETURN] repeats previous “step” or “next”  r return from function  t toggle trace mode
  • 56. Debugging in Perl  Breakpoints  b line set a breakpoint at line line  b sub set a breakpoint at subroutine sub  d line delete breakpoint  D delete all breakpoints  c [line] continue running until next breakpt [set a temporary breakpoint at line]  L List all breakpoints
  • 57. Debugging in Perl  Actions  a line cmd executes perl code cmd each time line is reached  A delete all line actions  < cmd set action right before the debugging prompt  > cmd set action right after the debugging prompt
  • 58. Debugging in Perl How to Learn More  man perldebug  just try it!
  • 59. CPAN Comprehensive Perl Archive Network  Hundreds of reusable Perl modules written by people on the Internet  Archive sites  ftp://ftp.cs.colorado.edu/pub/perl/CPAN/  ftp://ftp.cdrom.com/pub/perl/CPAN/  ftp://ftp.orst.edu/pub/packages/CPAN/
  • 60. How to Learn More  On-line man pages  man perl -- starting point man perldoc -- documentation man perlmod -- modules  perldoc command gives manpage-like info  example: perldoc Getopt::Std