Basic Perl Programming
Introduction:
• Perl - Practical Extraction and Report Language
• Using interpreter to run on the system (windows/unix/linux perl interpreter)
• Very powerful for handling and manipulate text
• Usually with *.pl file/script extension
1
Getting Perl
• In Linux/Unix OS it has become a standard package installed
• For Windows OS get it from:– http://www.activestate.com/– http://strawberryperl.com/
2
My first Perl program (Say hello to Perl)
#! /usr/bin/perl
# print a words "Say hello to Perl"
print "Say hello to Perl.\n";
Basic Perl Programming
3
Basic Standard Input/Output
#! /usr/bin/perl
print "\nPlease enter your name: ";
$user_name = <STDIN>;
print "\nHello ", $user_name,
"Please say hello to Perl\n";
Basic Perl Programming
4
Variable (Scalar)
• must be preceded with ‘$’ sign• no specific data types (int, float, char)
#! /usr/bin/perl
$food = "2-Piece Chicken";
$drink = "Pepsi";
print "Food = $food\n";
print "Drink = $drink\n\n";
$food = 4.59;
$drink = 1.7;
print "Food price= $food\n";
print "Drink price= $drink\n";
print "Total price= ", $drink + $food, "\n";
Basic Perl Programming
5
Exercise 1:
Write Perl script to ask student to enter name, e-mail, and course. The script will later print out all the information entered.
Basic Perl Programming
6
Variable (Array)
• preceded with ‘@’ sign
• several ways to define array:
@food = (“”);
$food[0] = “2-Piece Chickens”;
$food[1] = “Kentucky Nuggets (6 Pieces)”;
$food[2] = “Deli Burger”;
@drink = (“Pepsi”, “Ice Lemon Tea”, “Orange Juice”);
Basic Perl Programming
7
Variable (Array)
• syntax to get an array element:
$array_variable_name[index_value];
• retrieve the number of item and length of index of array variable:
$items = @drink # $ items will get the value of 3
$length = $#drink # $length will get the value of 2
Basic Perl Programming
8
Basic Perl Programming
Variable (Array)
• define and assign a value of array variable using split function
$f_price = “4.59 3.99 2.00”;
@food_price = split(/ /, $f_price);
@drink_price = split(/:/, “1.70:2.20:2.20”);
9
Basic Perl Programming
Exercise 2:
Modify the script from exercise 1 so it can handle more than single student information.
10
Basic Perl ProgrammingVariable (Hash)
• a series pairs of keys and values
• Preceded with “%” sign
• The syntax to define hash:
%hash_var = (key_1 => “value_1”, … , key_n => “value_n”
);
11
Basic Perl ProgrammingVariable (Hash)
• The other possible way to assign keys and values to hash:
%hash_var = undef;
$hash_var{key_1} = “value_1”;…$hash_var{key_n} = “value_n”;
12
Basic Perl Programming
Variable (Hash)
• Example:
%food = ("");
$food{fruit} = "Apple";
$food{animal} = "Beef";
%drink =(natural=>"Mineral Water",
carbonate=>"Coca-Cola");
13
Variable (Hash)
• syntax to get hash element:
$hash_var_name{key};
• get all keywords from hash and store it in an array
@array_var_name = keys(%hash_var_name);
Basic Perl Programming
14
Basic Perl Programming
Variable (Hash)
• Access hash keys name:
@keys = keys(%hash_var);
print "\$keys[0] = $keys[0] \n";print "\$keys[1] = $keys[1] \n";print "\$keys[.] = $keys[.] \n";print "\$keys[n] = $keys[n] \n";
15
Basic Perl Programming
Variable (Hash)
• Access and assign value to specific hash key:
print “$keys[0]= ” , $hash_var{$keys[0]}, “\n”;
$hash_var{$keys[0]} = “other value”;
print “$keys[0]= ” , $hash_var{$keys[0]}, “\n”;
16
Basic Perl Programming
Copying,Referencing & De-referencing Variable
• Copying variable:
$my_var = “hello”;$other_var = $my_var;
print “$my_var : $other_var \n”;
$other_var = “olleh”;
print “$my_var : $other_var \n”;
17
Basic Perl Programming
• Referencing & de-referencing variable:
$my_var = “hello”;$other_var = \$my_var;
print “$my_var : $$other_var \n”;
$$other_var = “olleh”;
print “$my_var : $$other_var \n”;
18
Basic Perl Programming
• Explanations:
$other_var = \$my_var; -> this will caused $other_var
store the address refer by
$my_var
$$other_var; -> this is the way we assign/access the value
stored by the address
$$other_var = “olleh”; -> this will caused address refer by both $my_var & $other_var had a new value (“olleh”)
19
Basic Perl Programming
• Referencing & de-referencing array & hash:
@my_array = (“One”, “Two”);%my_hash = (1 => “One”, 2 => “Two”);
$array_ref = \@my_array;$hash_ref = \%my_hash;
#de-referencing array & hash${$array_ref}[0] or $array_ref->[0]; ${$hash_ref}{2} or $hash_ref->{2};
#copy array & hash from reference @other_array = @{$array_ref}; %other_hash = %{$hash_ref};
20
Loop and control statement
Basic Perl Programming
if (…){} Executes when a specified condition is true
if (…) {} else {} Chooses between two alternatives
if (…){} elsif() {} else {} Chooses between more than two alternatives
for (…) {} Repeats a group of statements a specified number of times
foreach $var_name1 (@var_name2) Special loop to access all elements in array variable
while(…) {} Repeats a group of statements a specified number of times
21
Comparison Operators
Basic Perl Programming
Integer-Comparison Operators
Operator Description
< Less than
> Greater than
== Equal to
<= Less than or equal to
>= Greater than or equal to
!= Not equal to
22
Basic Perl Programming
Comparison Operators
String-Comparison Operators
Operator Description
lt Less than
gt Greater than
eq Equal to
le Less than or equal to
ge Greater than or equal to
ne Not equal to
23
Basic Perl Programming
Exercise 3:
Extend the script from exercise 2 so it can handle other new input (student’s CPA). Based on the CPA value determine either they get 1st, 2nd, or 3rd class following the given conditions below:
24
CPA Class
3.7 and above 1st
2.0 – 3.69 2nd
Below than 2.0 3rd
Pattern matching and string manipulation
The syntax for pattern matching:$string_variable =~ /pattern_to_match/opt;
Example:$str = “Hello World”; if ($str =~ /lo/) {
print “Found it.\n”;} else {
print “Not found.\n”;}
Basic Perl Programming
25
Basic Perl Programming
Pattern matching and string manipulation
The syntax for pattern replacement:$string_variable =~ s/pattern_to_replace/replacement/opts;
Example:$str = “Hello World”;$str =~ s/l/m/g;
26
Basic Perl Programming
Pattern matching and string manipulation
Options (opts) for pattern matching & replacement
Option Description
g Change all occurrences of the pattern
i Ignore case in pattern
e Evaluate replacement string as expression (only for substitution operator)
m Treat string to be matched as multiple lines
o Evaluate only once
s Treat string to be matched as single line
x Ignore white space in pattern
27
Basic Perl Programming
Pattern matching and string manipulation
Regular expression in the pattern (pattern_to_replace) Meta-characters Char Meaning Char Meaning
^ beginning of string ? match 0 or 1 times
$ end of string | alternative
. any character except newline () grouping
* match 0 or more times [] set of characters
+ match 1 or more times {} repetition modifier
To present these meta-characters as a character itself use the ‘\’ character before each meta-characters. Examples: \^, \$, …
http://www.cs.tut.fi/~jkorpela/perl/regexp.html 28
Basic Perl Programming
Pattern matching and string manipulation
Regular expression in the pattern (pattern_to_replace)
How to know if the string hold by the scalar $plate_no is a valid Johor’s car plate number?
- All letters must be capital start with ‘J’
^J
- The trailing letters not more than 2 and not including the ‘I’, ‘O’, and ‘Z’ letters
^J[A-H,J-N,P-Y]{1,2}
- Ending with numbers not starting with ‘0’ and not more than 4 in total
^J[A-H,J-N,P-Y]{1,2}[1-9]{1}[0-9]{0,3}
29
Basic Perl Programming
Pattern matching and string manipulation
String manipulation functions
Function Description
index (string, substring)
Identify the location of a substring in a string.
rindex (string, substring)
Similar to the index function but starts searching from the right end of the string.
length (string) Returns the number of characters contained in a character string.
substr (string, num_of_skip_char, length)
Returns a part of a character string.
lc(string) Converts a string to lowercase.
uc(string) Converts a string to uppercase. 30
Basic Perl Programming
Pattern matching and string manipulation
String concatenation:
#! /usr/bin/perl
$string1 = “The first string ”;$string2 = “The second string”; $my_string = $string1 . “ and ” . $string2 ;
print “$my_string \n”;
31
File Input/Output
Read Operation:
if(open(MYFILE, "<directory/file_name")){
@array_var = <MYFILE>;
. . .
. . .
. . .
close(MYFILE);
}
Basic Perl Programming
32
File Input/Output
Write Operation:
if(open(MYFILE, “>directory/file_name")) {
. . .
. . .
. . .
print MYFILE ($var_store_file_content);
close(MYFILE);
}
Basic Perl Programming
33
Basic Perl Programming
Exercise 4:
Modify the script from exercise 3 so the output would also be available as an HTML file. Use the template below as a basic structure of the HTML file content.
<html>
<body>
<table>
<tr><td>Name</td><td>CPA</td><td>Class</td></tr>
<tr><td>_name_</td><td>_cpa_</td><td>_class_</td></tr>
</table>
</body>
</html>34
Basic Perl ProgrammingSubroutine/Function
Create a subroutine in Perl script :
sub subroutine_name {
. . .
. . .
. . .
}
Calling a subroutine:
&subroutine_name; 35
Basic Perl ProgrammingSubroutine
Skeleton of perl script that using a subroutine:
#! /usr/bin/perl
. . .
. . .
&subroutine_name;
. . .
. . .
sub subroutine_name {
. . .
. . .
} 36
Basic Perl ProgrammingSubroutine
Example:#! /usr/bin/perl
print "Perl script welcoming the users.\n\n";
&welcome_user;
sub welcomeUser {
print "Your name please: ";
$name = <STDIN>;
chop($name);
print "\nHello $name, welcome to Perl world.\n\n";
} 37
Basic Perl ProgrammingSubroutine
Pass and return values to/from subroutine
• make a subroutine more flexible and useful
• based on three guidelines :
1. The subroutine can accept more than one scalar variable and only one array variable
2. If the subroutine accept both scalar and array variables the array variable must appear last in the arguments
3. The first two guidelines above can be ignored by passing array/hash as a reference 38
Basic Perl ProgrammingSubroutine
Pass and return values to/from subroutine
The Skeleton:
sub subroutine_name {
$scalar_var_name_1 = shift @_;
. . .
$scalar_var_name_n = shift @_;
@array_var_name = @_;
. . .
. . .
return (value);
} 39
Basic Perl ProgrammingSubroutine
Pass and return values to/from subroutine
Calling a subroutine that can accept and return values:
$var_name = &subroutine_name(scalar1, . . ., scalarN, array);
40
Basic Perl ProgrammingSubroutine
Pass and return values to/from subroutine
The story so far:
• To return a value the command: return (value); is used inside the subroutine where value can be either scalar, array or result of an expression
• When values passed to the subroutine, all the values are stored in the special array variable named @_
• The subroutine must extract all the values from this special array variable and pass it to the appropriate variables following the guidelines given previously 41
Basic Perl ProgrammingSubroutine
Pass and return values to/from subroutine
The story so far:
• To return a value the command: return (value); is used inside the subroutine where value can be either scalar, array or result of an expression
• When values passed to the subroutine, all the values are stored in the special array variable named as: @_
• The subroutine then must extract all the values from this special array variable and pass it to the appropriate variables using the two guidelines above 42
Basic Perl ProgrammingSubroutine
Pass and return values to/from subroutine
The story so far:
• The command: shift @_; will extract and shift the first item in @_
• The command: @array_var_name = @_; will assigns all the values of @_ to @array_var_name
• Example:
• Variable @_ contains the values: (“A”, “B”, “C”) • The command $var_name = shift @_ will extract the first item of @_
which is “A”, pass it to $var_name and left the @_ with the values: (“B”, “C”)
• The next command @var_name2 = @_ will make the variable @var_name2 contains the values: (“B”, “C”)
43
Basic Perl Programming
Exercise 5:
Modify the script from exercise 4 so the core tasks are written modularly using subroutines/functions.
44
Basic Perl ProgrammingSubroutine
Writing subroutines as a libraries
• The technique for writing a subroutine before caused the subroutine can only be used by the script who implementing them
• Writing subroutines as a libraries provide more flexible subroutine that can be used many times by other scripts
45
Basic Perl ProgrammingSubroutine
Writing subroutines as a libraries
• Skeleton for writing subroutine as a libraries:
package library_name;
subroutines goes here . . .
1;
• The scripts that are intended to be a libraries must be saved as library_name.pl
• The: 1; at the end of libraries script is a mandatory so the perl interpreter can call and run the libraries correctly 46
Basic Perl ProgrammingSubroutine
Writing subroutines as a libraries
• Calling and use subroutine from the libraries:
#! /usr/bin/perl
require (“library_name.pl");
. . .
$val = &library_name’subroutine_name1;
&library_name’subroutine_name2(. . .);
. . .
47
Basic Perl ProgrammingSubroutine
Variable scope:
#! /usr/bin/perl
$name = "Your name";
print "\$name: $name\n";
&change_name;
print "\Sname: $name\n";
sub change_name { my $name = "My name";}
#! /usr/bin/perl
$name = "Your name";
print "\$name: $name\n";
&change_name;
print "\Sname: $name\n";
sub change_name { $name = "My name";}
48
Top Related