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
48
Embed
Basic Perl Programming Introduction: Perl - Practical Extraction and Report Language Using interpreter to run on the system (windows/unix/linux perl interpreter)
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
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.
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: \^, \$, …
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.
• 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