PERL : Practical Extraction and Report Language
PERL Usage :
- text processing.
- system programming.
- web development.
- General purpose programming
Perl Interpret :
- No compilation
- Script:
- text file with commands
- They are executed line by line in sequence
Perl Syntax :
- Case Sensitive:
- Perl Comment: #
- Escape for special characters: \
Variable types and their uses
- Scalar An individual value (number or string) $
- Array A list of values, keyed by number @
- Hash A group of values, keyed by string %
- Subroutine A Perl function &
- Typeglob Everything named struck *
Scalars :
- my $value = 42; # an integer
- my $pi = 3.14159265; # a "real" number
- my $avocados = 6.02e23; # scientific notation
- my $pet = "Dog"; # string
- my $sign = "I have one $pet"; # string with interpolation
- my $cost = 'It costs $100'; # string without interpolation
- my $thence = $whence; # another variable's value
- my $salsa = $moles * $avocados; # a gastrochemical expression
- my $exit = system("vi $file"); # numeric status of a command
- my $cwd = `pwd`; # string output from a command
Fancy Values: We should point out that scalars may also hold references to other data structures, including subroutines and objects.
my $ary = \@myarray; # reference to a named array
my $hsh = \%myhash; # reference to a named hash
my $sub = \&mysub; # reference to a named subroutine
my $ary = [1,2,3,4,5]; # reference to an unnamed array
my $hsh = {Na => 19, Cl => 35}; # reference to an unnamed hash
my $sub = sub { print $state }; # reference to an unnamed subroutine
my $fido = Camel–>new("Amelia"); # reference to an object
new operator automatically initializes ‘undef’ to scalar var. Depending on context, this undef value might be interpreted as a slightly more defined null value, such as “” to 0.
Automatic Data Type Conversion :
Example String to number.
my $camels = "123";
print $camels + 1, "\n";
In Single quotes var '$var' will not be replaced with values, unlike double quotes . Example “\n” is new line but ‘\n’ is n which is not new line character.
my $camels = "123";
print $camels + 1, "\n";
In Single quotes var '$var' will not be replaced with values, unlike double quotes . Example “\n” is new line but ‘\n’ is n which is not new line character.
die :
Stops program execution. Message can be added.
Input from user :
print STDOUT "Enter a number: "; # ask for a number
$number = <STDIN>; # input the number, with new line char
# chomp($number = <STDIN>); # input a number, then remove its newline
say STDOUT "The number is $number."; # print the number
$number = <STDIN>; # input the number, with new line char
# chomp($number = <STDIN>); # input a number, then remove its newline
say STDOUT "The number is $number."; # print the number
Arrays [Short intro] : Ordered list of scalars.
my @home = ("couch", "chair", "table", “stove");
Conversely, if you use @home in list context, such as on the right side of a list assignment, you get back out the same list you put in. So you could create four scalar variables from the array like this:
Conversely, if you use @home in list context, such as on the right side of a list assignment, you get back out the same list you put in. So you could create four scalar variables from the array like this:
my ($potato, $lift, $tennis, $pipe) = @home;
These are called list assignments. They logically happen in parallel, so you can swap two existing variables by saying:
($alpha,$omega) = ($omega,$alpha);
Example 2 :
my @home;
$home[0] = "couch";
$home[1] = "chair";
$home[2] = "table";
$home[3] = "stove";
These are called list assignments. They logically happen in parallel, so you can swap two existing variables by saying:
($alpha,$omega) = ($omega,$alpha);
Example 2 :
my @home;
$home[0] = "couch";
$home[1] = "chair";
$home[2] = "table";
$home[3] = "stove";
Hashes [Brief intro]:
A hash is an unordered set of scalars, accessed9 by some string value that is associated with each scalar. For this reason hashes are often called associative arrays.
my %longday = (
"Sun" => "Sunday",
"Mon" => "Monday",
"Tue" => "Tuesday",
"Wed" => "Wednesday",
"Thu" => "Thursday",
"Fri" => "Friday",
"Sat" => "Saturday",
);
"Sun" => "Sunday",
"Mon" => "Monday",
"Tue" => "Tuesday",
"Wed" => "Wednesday",
"Thu" => "Thursday",
"Fri" => "Friday",
"Sat" => "Saturday",
);
Hash of Arrays [Brief intro]:
example hash with 1D array :
$wife{"Jacob"} = ["Leah", "Rachel", "Bilhah", "Zilpah"];
$wife{"Jacob"}[0] = "Leah";
$wife{"Jacob"}[1] = "Rachel";
$wife{"Jacob"}[2] = "Bilhah";
$wife{"Jacob"}[3] = "Zilpah";
example hash with hashes of array:
my %kids_of_wife;
$kids_of_wife{"Jacob"} = {
"Leah" => ["Reuben", "Simeon", "Levi", "Judah", "Issachar", "Zebulun"],
"Rachel" => ["Joseph", "Benjamin"],
"Bilhah" => ["Dan", "Naphtali"],
"Zilpah" => ["Gad", "Asher"],
};
can be accessed as
$wife{"Jacob"} = ["Leah", "Rachel", "Bilhah", "Zilpah"];
$wife{"Jacob"}[0] = "Leah";
$wife{"Jacob"}[1] = "Rachel";
$wife{"Jacob"}[2] = "Bilhah";
$wife{"Jacob"}[3] = "Zilpah";
example hash with hashes of array:
my %kids_of_wife;
$kids_of_wife{"Jacob"} = {
"Leah" => ["Reuben", "Simeon", "Levi", "Judah", "Issachar", "Zebulun"],
"Rachel" => ["Joseph", "Benjamin"],
"Bilhah" => ["Dan", "Naphtali"],
"Zilpah" => ["Gad", "Asher"],
};
can be accessed as
$kids_of_wife{"Jacob"}{"Leah"}[0] = “Reuben";
1)package Camel;
our $fido = &fetch();
2) package Dog;
our $fido = &fetch();
Then $Camel::fido is different from $Dog::fido
use Camel;
my $fido = Camel->new(“Amelia”);
open(SESAME, "< filename”); # ( same thing , explicitly)
open(SESAME, "> filename”); # create file and write to it
open(SESAME, ">> filename”); #append to existing file
open(SESAME, "| output–pipe–command") ; # set up an output filter
open(SESAME, "input–pipe–command |") ; # set up an input filter
Open also lets you specify the character encoding of the file.
open(SESAME, "< :encoding(UTF–8)", $somefile)
open(SESAME, "> :crlf", $somefile)
open(SESAME, ">> :encoding(MacRoman)", $somefile)
2) String : . [concat], x [distinct numeric multiplication]
ex.
$a=123; $b=3;
say $a . $b; # 1233
say $a x $b; # 123123123
other examples:
say $a . " is equal to " . $b . “."; # dot operator
say $a, " is equal to ", $b, “."; #list
say "$a is equal to $b.”; # interpolation
some other examples:
$line .= "\n"; # Append newline to $line.
$fill x= 80; # Make string $fill into 80 repeats of itself.
$val ||= "2"; # Set $val to 2 if it isn't already "true".
3) Assignment Operator :
$a = $b = $c = 0;
4) Unary Arithmetic Operators :
++a, a++, —a, a—
5) Logical Operators :
&&,||, !, and, or, not, xor
6) Comparison Operators :
Numeric ==, !=, < , > , <=, >=, <=>
ex.
$a <=> $b # 0 if equals, 1 if $a greater, -1 if $b greater
String eq,ne,lt,gt,le,ge,cmp
ex.
$a cmp $b # 0 if equals, 1 if $a greater, -1 if $b greater
7) Some File Test Operators
–e $a Exists True if file named in $a exists
–r $a Readable True if file named in $a is readable
–w $a Writable True if file named in $a is writable
–d $a Directory True if file named in $a is a directory
–f $a File True if file named in $a is a regular file
–T $a Text File True if file named in $a is a text file
Can be used like this:
–e "/usr/bin/perl" or warn "Perl is improperly installed.\n";
–f "/vmlinuz" and say "I see you are a friend of Linus.”;
1 # would become the string "1", so true.
10 – 10 # 10 minus 10 is 0, would convert to string "0", so false.
0.00 # equals 0, would convert to string "0", so false.
"0" # is the string "0", so false.
"" # is a null string, so false.
"0.00" # is the string "0.00", neither "" nor "0", so true!
"0.00" + 0 # would become the number 0 (coerced by the +), so false.
\$a # is a reference to $a, so true, even if $a is false.
undef() # is a function returning the undefined value, so false.
1) if
if ($city eq "New York") {
say "New York is northeast of Washington, D.C.";
}elsif ($city eq "Chicago") {
say "Chicago is northwest of Washington, D.C.";
}elsif ($city eq "Miami") {
say "Miami is south of Washington, D.C. And much warmer!";
}else {
say "I don't know where $city is, sorry.";
}
2) unless [if !true ]
unless ($destination eq $home) {
say "I'm not going home.”;
}
3) given and when [switch case]
ex.
print "What is your favorite color? ";
chomp(my $answer = <STDIN>);
given ($answer) {
when ("purple") { say "Me too." }
when ("green") { say "Go!" }
when (/\w+, no \w+/) { die "AAAUUUGHHHHH!" }
when (42) { say "Wrong answer." }
when (['gray','orange','brown','black','white']) {
say "I think $answer is pretty okay too.";
}
default {
say "Are you sure $answer is a real color?";
}
}
while (@ARGV) { shift @ARGV;,…}
2) for
a) for (my $sold = $before; $sold < 10000; $sold += my $purchase) {
my $available = 10000 – $sold;
print "$available tickets are available. How many would you like: ";
$purchase = <STDIN>;
if ($purchase > $available) {
say "Too many! Try again.";
$purchase = 0;
}
}
b) for (;;) {
say "Take out the trash!";
}
c) for my $key (sort keys %hash) {
d) for my $user (@users) {
next [continue] , last [break]
Whitespace \t\n\r\f \s
Word character [a-zA-Z_0-9] \w
Digit [0-9] \d
Quantifiers
\w+ multiple words chars
\d{7,11} 7 digits but not more than 11
We’ve already seen +, which is the same as {1,}, or “at least one of the preceding item”. There is also *, which is the same as {0,}, or “zero or more of the preceding item”, and ?, which is the same as {0,1}, or “zero or one of the preceding item”
minimal matching
/.*?:/
/b matches at a word boundary,which is defined as the “nothing” between a word character (\w) and a nonword character (\W), in either order. (The characters that don’t exist off the beginning and end of your string are considered to be nonword characters.) For example:
/\bFred\b/
would match “Fred” in both “The Great Fred” and “Fred the Great”, but not in “Frederick the Great” because the “d” in “Frederick” is not followed by a non- word character.
In a similar vein, there are also anchors for the beginning and the end of the string. If it is the first character of a pattern, the caret (^) matches the “nothing” at the beginning of the string. Therefore, the pattern /^Fred/ would match “Fred” in “Frederick the Great” but not in “The Great Fred”, whereas /Fred^/ wouldn’t match either.
The dollar sign ($) works like the caret, except that it matches the “nothing” at the end of the string instead of the beginning.32 So now you can probably figure out that when we said:
next LINE if $line =~ /^#/; we meant “Go to the next iteration of LINE loop if this line happens to begin with a # character.”
topicalization [Brief Intro]
package :
example :1)package Camel;
our $fido = &fetch();
2) package Dog;
our $fido = &fetch();
Then $Camel::fido is different from $Dog::fido
use :
Before using packages in another package, we’ll need to import it using ‘use’.use Camel;
my $fido = Camel->new(“Amelia”);
File Handlers [Brief Intro.]
open(SESAME, “filename") ; #read from existing fileopen(SESAME, "< filename”); # ( same thing , explicitly)
open(SESAME, "> filename”); # create file and write to it
open(SESAME, ">> filename”); #append to existing file
open(SESAME, "| output–pipe–command") ; # set up an output filter
open(SESAME, "input–pipe–command |") ; # set up an input filter
Open also lets you specify the character encoding of the file.
open(SESAME, "< :encoding(UTF–8)", $somefile)
open(SESAME, "> :crlf", $somefile)
open(SESAME, ">> :encoding(MacRoman)", $somefile)
Operators :
1) Binary Arithmetic : +,*,%,**[exponential]2) String : . [concat], x [distinct numeric multiplication]
ex.
$a=123; $b=3;
say $a . $b; # 1233
say $a x $b; # 123123123
other examples:
say $a . " is equal to " . $b . “."; # dot operator
say $a, " is equal to ", $b, “."; #list
say "$a is equal to $b.”; # interpolation
some other examples:
$line .= "\n"; # Append newline to $line.
$fill x= 80; # Make string $fill into 80 repeats of itself.
$val ||= "2"; # Set $val to 2 if it isn't already "true".
3) Assignment Operator :
$a = $b = $c = 0;
4) Unary Arithmetic Operators :
++a, a++, —a, a—
5) Logical Operators :
&&,||, !, and, or, not, xor
6) Comparison Operators :
Numeric ==, !=, < , > , <=, >=, <=>
ex.
$a <=> $b # 0 if equals, 1 if $a greater, -1 if $b greater
String eq,ne,lt,gt,le,ge,cmp
ex.
$a cmp $b # 0 if equals, 1 if $a greater, -1 if $b greater
7) Some File Test Operators
–e $a Exists True if file named in $a exists
–r $a Readable True if file named in $a is readable
–w $a Writable True if file named in $a is writable
–d $a Directory True if file named in $a is a directory
–f $a File True if file named in $a is a regular file
–T $a Text File True if file named in $a is a text file
Can be used like this:
–e "/usr/bin/perl" or warn "Perl is improperly installed.\n";
–f "/vmlinuz" and say "I see you are a friend of Linus.”;
Control Structures:
True / False
0 # would become the string "0", so false.1 # would become the string "1", so true.
10 – 10 # 10 minus 10 is 0, would convert to string "0", so false.
0.00 # equals 0, would convert to string "0", so false.
"0" # is the string "0", so false.
"" # is a null string, so false.
"0.00" # is the string "0.00", neither "" nor "0", so true!
"0.00" + 0 # would become the number 0 (coerced by the +), so false.
\$a # is a reference to $a, so true, even if $a is false.
undef() # is a function returning the undefined value, so false.
1) if
if ($city eq "New York") {
say "New York is northeast of Washington, D.C.";
}elsif ($city eq "Chicago") {
say "Chicago is northwest of Washington, D.C.";
}elsif ($city eq "Miami") {
say "Miami is south of Washington, D.C. And much warmer!";
}else {
say "I don't know where $city is, sorry.";
}
2) unless [if !true ]
unless ($destination eq $home) {
say "I'm not going home.”;
}
3) given and when [switch case]
ex.
print "What is your favorite color? ";
chomp(my $answer = <STDIN>);
given ($answer) {
when ("purple") { say "Me too." }
when ("green") { say "Go!" }
when (/\w+, no \w+/) { die "AAAUUUGHHHHH!" }
when (42) { say "Wrong answer." }
when (['gray','orange','brown','black','white']) {
say "I think $answer is pretty okay too.";
}
default {
say "Are you sure $answer is a real color?";
}
}
Looping :
1) while
while (my $line <1000 ) { …}
while (my $line = <GRADES>) { …}while (@ARGV) { shift @ARGV;,…}
2) for
a) for (my $sold = $before; $sold < 10000; $sold += my $purchase) {
my $available = 10000 – $sold;
print "$available tickets are available. How many would you like: ";
$purchase = <STDIN>;
if ($purchase > $available) {
say "Too many! Try again.";
$purchase = 0;
}
}
b) for (;;) {
say "Take out the trash!";
}
c) for my $key (sort keys %hash) {
d) for my $user (@users) {
next [continue] , last [break]
Regular Expressions :
Shortcuts for alphabetic charactersWhitespace \t\n\r\f \s
Word character [a-zA-Z_0-9] \w
Digit [0-9] \d
Quantifiers
\w+ multiple words chars
\d{7,11} 7 digits but not more than 11
We’ve already seen +, which is the same as {1,}, or “at least one of the preceding item”. There is also *, which is the same as {0,}, or “zero or more of the preceding item”, and ?, which is the same as {0,1}, or “zero or one of the preceding item”
minimal matching
/.*?:/
/b matches at a word boundary,which is defined as the “nothing” between a word character (\w) and a nonword character (\W), in either order. (The characters that don’t exist off the beginning and end of your string are considered to be nonword characters.) For example:
/\bFred\b/
would match “Fred” in both “The Great Fred” and “Fred the Great”, but not in “Frederick the Great” because the “d” in “Frederick” is not followed by a non- word character.
In a similar vein, there are also anchors for the beginning and the end of the string. If it is the first character of a pattern, the caret (^) matches the “nothing” at the beginning of the string. Therefore, the pattern /^Fred/ would match “Fred” in “Frederick the Great” but not in “The Great Fred”, whereas /Fred^/ wouldn’t match either.
The dollar sign ($) works like the caret, except that it matches the “nothing” at the end of the string instead of the beginning.32 So now you can probably figure out that when we said:
next LINE if $line =~ /^#/; we meant “Go to the next iteration of LINE loop if this line happens to begin with a # character.”
No comments:
Post a Comment