0% found this document useful (0 votes)
25 views

PERL in 8 Hours, For Beginners, Learn Coding Fast! - Perl Programming (BooksRack - Net)

Uploaded by

maxwellmbalako37
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

PERL in 8 Hours, For Beginners, Learn Coding Fast! - Perl Programming (BooksRack - Net)

Uploaded by

maxwellmbalako37
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 120

Perl

In 8 Hours

For Beginners
Learn Coding Fast!

Ray Yao
Copyright © 2015 by Ray Yao
All Rights Reserved
Neither part of this book nor whole of this book may be reproduced or
transmitted in any form or by any means electronic, photographic or
mechanical, including photocopying, recording, or by any information
storage or retrieval system, without prior written permission from the author.
All rights reserved!
Ray Yao

About the Author: Ray Yao


Certified PHP engineer by Zend, USA
Certified JAVA programmer by Sun, USA
Certified SCWCD developer by Oracle, USA
Certified A+ professional by CompTIA, USA
Certified ASP. NET expert by Microsoft, USA
Certified MCP professional by Microsoft, USA
Certified TECHNOLOGY specialist by Microsoft, USA
Certified NETWORK+ professional by CompTIA, USA
www.amazon.com/author/ray-yao
“In 8 Hours” eBooks & Books on Amazon
Advanced C++ in 8 Hours
Advanced Java in 8 Hours
AngularJs in 8 Hours
C# in 8 Hours
C# Q & A
C++ in 8 Hours
C++ Q & A
Django in 8 Hours
Go in 8 Hours
Html Css in 8 Hours
Html Css Q & A
Java in 8 Hours
Java Q & A
JavaScript in 8 Hours
JavaScript Q & A
JQuery in 8 Hours
JQuery Q & A
Kotlin in 8 Hours
Linux Command Line
Linux Q & A
MySql in 8 Hours
Node.Js in 8 Hours
Perl in 8 Hours
Php MySql in 8 Hours
Php Q & A
PowerShell in 8 Hours
Python in 8 Hours
Python Q & A
R in 8 Hours
Ruby in 8 Hours
Rust in 8 Hours
Scala in 8 Hours
Shell Scripting in 8 Hours
Swift in 8 Hours
Visual Basic in 8 Hours
Visual Basic Q & A
Xml Json in 8 Hours
Preface
“Perl in 8 Hours” covers all essential Perl language knowledge. You can
learn complete primary skills of Perl programming fast and easily.
The book includes more than 60 practical examples for beginners and
includes tests & answers for the college exam, the engineer certification
exam, and the job interview exam.

Note:
This book is only for Perl beginners, it is not suitable for experienced Perl
programmers.

Source Code for Download


This book provides source code for download; you can download the source
code for better study, or copy the source code to your favorite editor to test
the programs.
Table of Contents

Hour 1
What is Perl?
Install Perl
Run First Program of Perl
Perl Comment
Data Type
Escape Sequences
Print
Here Document
Identifier
Hour 2
Variable
Constant
String
Array
Element Range
Array Size
The First Element
The Last Element
Extract Elements
Sort Elements
Conversion
Merge Arrays
Hour 3
Hash
Check Existing
Get Hash Values
Hash Size
Add or Remove Element
Iterate Through Hash
Arithmetical Operators
Comparison Operators
Logical Operators
Assignment Operators
Dot Operators
Increase & Decrease
Hour 4
If Statement
If-Else Statement
Unless Statement
Unless Statement
Ternary Operators
While Loop
Do…While Loop
Until Loop
For Loop
Foreach Loop
Continue
Last
Hour 5
Local & Greenwich Time
Subprogram
Subprogram With Parameters
Return
Public & Private Variable
Static Variable
Reference
Cancel Reference
Format Output (1)
Format Output (2)
Hour 6
Open a File
Write to File
Read from File
Input by User
File Copy
File Rename
File Remove
File Information
Directory Operation
Create a Directory
Open & Read a Directory
Change & Remove a Directory
Hour 7
Die Function
Warn Function
Sysopen Function
Match Operator
RegExp Variable
Substitute Operator
Lowercase & Uppercase Convert
Remove Double Character
Delete Specified Characters
Default Variable
Show the Perl comments
Hour 8
Class & Object
Constructor
Class & Object Example
Define a Method
Inheritance
Package
BEGIN & END Modules
Module
Require

Appendix Perl Q & A


Questions:
Answers:

Source Code Download


Hour 1
What is Perl?

Perl is an abbreviation for “Practical Extraction Report Language”.


Perl language is an interpreted scripting language, which was developed by
Larry Wall in 1986 as a scripting language designed to handle system-
oriented tasks in Unix environments. Perl has a strong ability to transform
files and characters, it is especially suitable for tasks related to system
management database and network interconnection as well as WWW
programming, which makes Perl the tool language of choice for system
maintenance managers and CGI programmers.
Perl is a high-level, universal, literal, dynamic programming language.
The most important features of Perl are the built-in integration of regular
expression capabilities, as well as the huge third-party code library CPAN.
Perl can easily do the following tasks: 1. Text data processing. 2. Network
program processing. 3. Database processing. 4. XML document processing.
5. System maintenance processing. 6. Image processing.
Install Perl

Download Perl
The official download link of Perl is as follows:
http://strawberryperl.com/

Install Perl
After downloading the Perl, Please double click it, and start to install Perl by
following the instruction of the installer.

Click “Next” button to install the Perl step by step……


When the installation is complete, please click the “Finish” button.

Create a Working Folder


In order to run Perl program easily, we can create a working folder in the root
directory of C: disk. The working folder will be named “myPerl”. For
example:
C:\myPerl

All Perl files will be saved in the working folder “myPerl”.


Run First Program of Perl
1. Click the Perl (Command Line) icon, open the Perl as follows:

2. Access the working folder “myPerl” in C: disk.


Please enter “cd C:\myPerl”, specify the “myPerl” as a current working
folder.

3. Open the Notepad, input the following Perl code to the Notepad editor.

# It will output "Hello, World"


print "Hello, world!";

Save the file named “Hello.pl” to the folder “myPerl”.


4. In Perl (Command Line), enter “perl Hello.pl” to execute this Perl
program.
You can see the output: “ Hello, world! ”

Congratulation! Your first Perl program run successfully!

The syntax to run a Perl program with Command Line is as follows:


perl filename.pl

“.pl” is an extension name of Perl.


Perl Comment

#
# is used to single-line comment.

=pod
……
……
=cut
“=pod……=cut” is used to multi-line comment.

Example 1.1

print "Hello!"; # single-line comment


=pod
multi-line comment
multi-line comment
multi-line comment
=cut

Output: Hello!
Explanation: The Perl interpreter will ignore the comments.
Data Type
Perl has various basic data types, such as variables, arrays, hashes, integer,
floating point, and string.

1. Variable
The value of a variable may change at runtime.
The “$” symbol is used to declare a variable.
For example: $myVariavle

2. Array
The array is a special variable, which contains a series of values.
The “@” symbol is used to declare an array.
For example: @myArray

3. Hash
A hash is an unordered collection of key/value pairs.
The “%” symbol is used to declare a hash.
For example: %myHash

4. Integer
Integer means the number without decimal places.
For example: 100

5. Floating Point
The floating point means the number with decimal places.
For example: 2.718

6. String
The string consists of a series of characters, spaces and numbers.
A string is always enclosed with double quotes or single quotes.
For example: “ myString ”

Example 1.2

$int = 100; # define an integer


$str = " Good "; # define a string
$flt = 2.718; # define a floating point
print $int, $str, $flt;
Output: 100 Good 2.718
Explanation:
$int, $str and $flt are integer, string and floating point variables.
Escape Sequences
The “ \ ” backslash character can be used to escape characters.
\b makes a backspace
\n outputs content to the next new line.
\r makes a return
\t makes a tab
\’ outputs a single quotation mark.
\” outputs a double quotation mark.
Example 1.3
print("He said \"Hello \n World! \"");
// \” outputs a double quote
// \n outputs contents to a new line.

Output:
He said "Hello
World! "
Explanation:
\” outputs a double quotation mark.
\n outputs the contents into a new line.
Print
Print command is used to output contents.
print “……”
print ‘……’

print “……” will output an interpreted value or a calculated value by using


double quotes.
print ‘……’ will output an original value by using single quotes.
Example 1.3

$score = 100; # $score is a variable


print "$score \n"; # using double quotes
print '$score \n'; # using single quotes

Output:
100
$score \n
Explanation:
The contents inside the double quotes can be interpreted.
The contents inside the single quotes cannot be interpreted, the output is the
original values.
Here Document
"Here Document" is used to define a series of texts and output multi-line
texts.
The syntax of “Here Document” is as follows:
<< "Here";
……
Here

Example 1.4
$var = << "Here";
"Here Document" can define a series of texts. \n
"Here Document" can show multi-line texts.
Here
print "$var";

Output:
"Here Document" can define a series of texts.
"Here Document" can show multi-line texts.
Explanation:
“<<"Here";……Here” is a Here Document.
Identifier
An identifier is a name when the programmer writes the code. The variable
name, constant name, function name, block name used in the program are
collectively referred to as identifiers.

For example:
The identifier $myVariable is a variable name.
The identifier @myArray is an array name.
The identifier %myHash is a hash name.

The rule of the Perl identifier is as follows:


1. Identifiers consist of letters (a~z, A~Z), numbers (0~9) and underscores ( _
). e.g. $mark_10 is a variable name.
2. Identifiers begin with letters or underscores, and cannot begin with
numbers. e.g. $10score is an invalid variable name.
3. Identifiers are case sensitive.
e.g. $myVariable and $MyVariable represent two different variable names.
Hour 2
Variable
The value of the variable is changeable at runtime.
“$” can be used to declare a variable. Its syntax is:

$variable = value
Variables do not need to declare a data type.

Example 2.1
$myVariable = "Hello, World!";
print $myVariable;

Output:
Hello, World!

Explanation:
“$” is a variable symbol.
“myVariable” is a variable name.
In Perl, each instruction is ended with a semicolon (;).
Constant
The value of the constant is unchangeable at runtime.
The syntax to define a constant is as follows:
use constant CONSTANT_NAME => value;

The constant name is usually capitalized.


Example 2.2
use constant MON => "Monday";
use constant SUN => "Sunday";
print MON ."\n";
print SUN ."\n";
Output:
Monday
Sunday
Explanation:
“use constant MON” defines a constant name “MON”.
“use constant SUN” defines a constant name “SUN”.
“.\n” is used to output the string value in the next line.
String
The string consists of a series of characters, spaces, numbers.
The string is always enclosed by double quotes or single quotes.
The dot “.” symbol can connect two strings.

Example 2.3
$str1 = "Shell Scripting";
$str2 = " in 8 Hours";
$myString = $str1 . $str2;
print $myString;
Output:
Shell Scripting in 8 Hours
Explanation:
"Shell Scripting" is a string enclosed by a double quote.
“$str1 . $str2” connects two strings by using a dot “.” symbol.
Array
The array is a special variable that contains a series of values, the array can
be a different data type.
The syntax to create an array is as follows:
@arrayName = (val1, val2, val3)

“val1, val2, val3” is three element values of the array.

The syntax to access an array element is:


$arrayName [index]

“index” is the element number, it begins with zero


Example 2.4
@book = ("Go", " in", " 8 Hours"); # create an array
print "$book[0]"; # the index is 0, accesses “Go”
print "$book[1]"; # the index is 1, accesses “in”
print "$book[2]"; # the index is 2, accesses “ 8 Hours”

Output: Go in 8 Hours
Explanation:
“@book” is the name of the array, which contains three elements.
Element Range
The range (startValue .. endValue) can access all elements from the
startValue to the endValue, its syntax is as follows:

(startValue .. endValue)
“(startValue .. endValue)” represents all elements from startValue to
endValue.
Example 2.5
@array1 = (0..8); # create an array
@array2 = (A..N); # create an array
print "@array1\n"; # output from 0 to 8
print "@array2\n"; # output from A to N
Output:
012345678
ABCDEFGHIJKLMN
Explanation:
“(0..8)” represents all elements from 0 to 8.
“(A..N)” represents all elements from A to N.
Array Size
The syntax to get the size of an array is:

$size = @arrayName;
print $size
“@arrayName” can get the size of an array.
The value of $size will be the length of the array.

Example 2.6
@myArray=(1,2,3,4,5,6);
$len=@myArray;
print "The size of myArray is $len";
Output:
The size of myArray is 6
Explanation:
“$len=@myArray;” assigns the value of myArray size to $len.
The First Element
The syntax to add an element to the beginning of an array is:
unshift(@array, newElement);

The syntax to remove the first element of an array is:

shift(@array);

Example 2.7
@arr = ("A","B","C"); # create an array
unshift(@arr, "OK"); # add an element "OK" to the beginning
print " $arr[0]", " $arr[1]", " $arr[2]", " $arr[3]";
print "\n";
shift(@arr); # remove the first element "OK"
print " $arr[0]", " $arr[1]", " $arr[2]";

Output:
OK A B C
A B C
Explanation:
“unshift()” and “shift()” adds or removes the first element.
The Last Element
The syntax to add an element to the end of an array is:
push(@array, "newElement");

The syntax to remove the last element of an array is:

pop(@array);

Example 2.8

@arr = ("A","B","C"); # create an array


push(@arr, "OK"); # add an element "OK" to the end
print " $arr[0]", " $arr[1]", " $arr[2]", " $arr[3]";
print "\n";
pop(@arr); # remove the last element "OK"
print " $arr[0]", " $arr[1]", " $arr[2]";

Output:
A B C OK
A B C
Explanation:
“push()” and “pop()” adds or removes the last element.
Extract Elements
The syntax to extract some elements from an array is:

@array[index1, index2, index3…];


“index1, index2, index3…” specifies the elements to extract by index.

Example 2.9
@arr1 = ("A","B","C", "D", "E", "F");
@arr2 = @arr1[1,3,5]; // extract elements by index
print @arr2;
Output:
BDF
Explanation:
“@arr1[1,3,5]” extracts the elements by index1, index3, index5, their values
are B, D, F respectively.
By the way, you can also use Range to extract elements
For example: @myArray[index1 .. index2].
Sort Elements
The syntax to sort all elements of an array is:

sort(@array);

Example 2.10
# create an array
@arr = ("E","D","B", "F", "A", "C");
print "Before sorting: @arr\n";
@arr = sort(@arr); # sort the array
print "Having sorted: @arr\n";
Output:
Before sorting: E D B F A C
Having sorted: A B C D E F
Explanation:
“sort(@arr)” sorts all elements of the array.
Conversion
A string can be converted to an array, and an array can also be converted to a
string.

@array = split('seperator', $string); # convert string to array


$string = join( 'seperator', @arring ); # convert array to string
“seperator” can be a space, “*”, “-”, “#”, “@”……
Example 2.11
$myStr = "Hello My Friends"; # create a string
@arr = split(' ', $myStr); # convert to array
$str = join( '**', @arr ); # convert to string
print "$arr[0] $arr[1] $arr[2] \n";
print "$str\n";

Output:
Hello My Friends
Hello**My**Friends
Explanation:
“split()” can convert a string to an array.
“join()” can convert an array to a string.
Merge Arrays
The syntax to merge two arrays is as follows:

(@array1, @array2)

Example 2.12
@arr1 = ("Shell", "Scripting");
@arr2 = ("in", "8", "Hours");
@mergeArr = (@arr1, @arr2); // merge two arrays
print "@mergeArr";

Output:
Shell Scripting in 8 Hours

Explanation:
“(@arr1, @arr2)” merges two arrays.
Hour 3
Hash
A hash is a collection of “key/value”. The symbol “%” is used to make a
hash name. ${key} is used to access a hash element.
The syntax to create a hash is as follows:
%hash = ('key1'=>'val1', 'key2'=>'val2', 'key3'=>'val3',...);

Example 3.1
%score = ('60'=>'passed', '85'=>'ok', '100'=>'excellent');
print "$score{'60'}\n";
print "$score{'85'}\n";
print "$score{'100'}\n";
Output:
passed
ok
excellent
Explanation:
“%score = (…)” creates a hash with three elements.
"$score{'60'}” accesses the element whose key is 60.
Check Existing
The exists() function can check whether the key/value is existing, If a
key/value pair does not exist, the “undefined” value is returned. The syntax to
use the exists() is as follows:

exists($hash{'key'})

Example 3.2

%score = ('60'=>'passed', '85'=>'ok', '100'=>'excellent');


if( exists($data{'90'} ) ){ # chick existing
print "The score 90 is $data{'90'} \n";
}
else{
print "The score 90 is not existing.";
}

Output:
The score 90 is not existing.
Explanation:
“exists($data{'90'}” checks whether the key “90” and its value exist.
Get Hash Values
The syntax to get all values of the hash is as follows:
@array = values %hash

The above returns an array containing all values of the hash.


Example 3.3

%score = ('60'=>'passed', '85'=>'ok', '100'=>'excellent');


@arr = values %score; # get all element values of the hash
print "$arr[0]\n";
print "$arr[1]\n";
print "$arr[2]\n";

Outout:
passed
ok
excellent
Explanation:
The output is unordered.
“values %score” gets all the values of the hash “score”, and returns an array
include these values.
Hash Size
The syntax to get the hash size is as follows:

@array = keys %hash; # get all keys in the hash


$size = @array; # get the total number of keys

Example 3.4
%score = ('60'=>'passed', '85'=>'ok', '100'=>'excellent');
@arr = keys %score;
$size = @arr;
print "The total number of the keys is: $size\n";
Output:
The total number of the keys is: 3
Explanation:
“@arr = keys %score;” gets all keys in the hash “score”, and returns an array
including these keys.
“$size = @arr;” gets the total number of keys.
Add or Remove Element

$hash{'key'} = 'value'; # add a hash element


delete $hash{'key'}; # remove a hash element

Explanation 3.5
%score = ('60'=>'passed', '85'=>'ok', '100'=>'excellent');
$score{'101'} = 'superhero!'; # add an element
delete $score{'60'}; # remove an element
@arr = values %score;
print "$arr[0] ";print "$arr[1] ";print "$arr[2] ";
Output:
ok excellent superhero
Explanation:
The output is unordered.
“$score{'101'} = 'superhero!';” adds an element “superhero” to the hash.
“delete $score{'60'};” removes an element whose key is 60 in the hash.
Iterate Through Hash

foreach $key (keys %hash){


}
“foreach $key (keys %hash){…}” is used to iterate through the elements of
the hash.
Example 3.6
%score = ('60'=>'passed', '85'=>'ok', '100'=>'excellent');
foreach $key (keys %score){
print "$score{$key}\n";
}
Output:
passed
ok
excellent
Explanation:
“foreach $key (keys %score){…}” iterates through the elements of the hash
“%score”.
Arithmetical Operators

Operators Running
+ add or connect strings
- subtract
* multiply
/ divide
% get modulus
** power

Example 3.7

$a = 4; $b = 2;
$c = $a + $b;
print '$a + $b = ' . $c . "\n"; # output: $a + $b = 6
$c = $a * $b;
print '$a * $b = ' . $c . "\n"; # output: $a * $b = 8
$c = $a % $b;
print '$a % $b = ' . $c. "\n"; # output: $a % $b = 0
$c = $a ** $b;
print '$a ** $b = ' . $c . "\n"; # output: $a ** $b = 16
Comparison Operators

Operators Running Returns


> greater than true or false
< less than true or false
>= greater than or equal true or false
<= less than or equal true or false
== equal true or false
!= not equal true or false

For example:
$x=100;
$y=200;
($x == $y) returns false
($x != $y) returns true
($x >= $y) returns false
($x <= $y) returns true
Logical Operators

Operators Result

and If both operands are true, returns true

or If one of the operands is true, returns true

not If the operand is true, returns false

For example:
$x=true;
$y=false;
($x and $y) returns false
($x or $y) returns true
not($x) returns false
not($y) returns true
Assignment Operators
Operators Examples: Equivalent:
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y
**= x**=y x=x**y

Example 3.8
$x = 100; $y = 200;
$y += $x; print "$y\n"; # $y=$y+$x output: 300
$x = 100; $y = 200;
$y *= $x; print "$y\n"; # $y=$y*$x output: 20000
$x = 100; $y = 200;
$y /= $x; print "$y\n"; # $y=$y/$x output: 2
$x = 100; $y = 200;
$y %= $x; print "$y\n"; # $y=$y%$x output: 0
Dot Operators

Operators Usage Result


. string . string connect two strings
.. num1 .. num2 from num1 to num2
Example 3.9
$x = "Very "; $y = "Good! ";
$result = $x . $y;
print "\$x . \$y = $result\n";
@result = (1..8);
print "(1..8) = @result\n";
Output:
$x . $y = Very Good!
(1..8) = 1 2 3 4 5 6 7 8
Explanation:
“$x . $y” connects two strings “Very” and “Good”.
“(1..8)” returns a range from 1 to 8.
Increase & Decrease
++ add 1
- - subtract 1

Example 3.10

$x= 100;
$x++; # x increases 1
$result = $x ;
print "\$x++ = $result\n";

$y = 100;
$y- -; # y decreases 1
$result = $y ;
print "\$y-- = $result\n";
Output: $x++ = 10
$y- - = 99
Explanation:
“$x++” # x increases 1
“$y- -” # y decreases 1
Hour 4
If Statement

if (boolean_expression){
# code
}
If the boolean expression returns true, the code within the if statement will be
executed. If returns false, will not be executed.

Example 4.1
$num = 100;
if( $num < 200 ){
printf "The num is less than 200\n";
}
Output:
The num is less than 200
Explanation:
Because “if($num<200)” returns true, the code within the “if statement” has
been executed, and prints the result.
If-Else Statement
if (boolean_expression){
# code1
} else {
# code2
}
If the boolean expression returns true, the code1 within the if statement will
be executed. If returns false, the code2 within the else statement will be
executed.
Example 4.2
$num = 300;
if( $num < 200 ){
printf "The num is less than 200\n";
} else {
printf "The num is greater than 200\n";
}

Output: The num is greater than 200


Explanation:
Because “if( $num < 200 )” returns false, the code within the else statement
has been executed, and prints the result.
Unless Statement

unless(boolean_expression){
# execute when boolean_expression returns false
}
“unless(boolean_expression)” returns false, the code within the unless
statement will be executed
Example 4.3
$num = 300;
unless( $num < 200 ){
printf "The num is greater than 200\n";
}
Output:
The num is greater than 200
Explanation:
Because “unless($num<200)” returns false, the code within the unless
statement has been executed, and prints the result.
Unless Statement
unless(boolean_expression){
# execute when boolean_expression returns false
} else {
# execute when boolean_expression returns true
}
“unless(boolean_expression)” returns false, the code within the unless
statement will be executed. If returns true, the code within the else statement
will be executed.
Example 4.4
$num = 100;
unless( $num < 200 ){
print "The num is greater than 200\n";
} else {
print "The num is less than 200\n";
}

Output: The num is less than 200


Explanation:
Because “unless( $num < 200 )” returns true, the code within the else
statement has been executed, and prints the result.
Ternary Operators
The ternary operators are “ ? : ”.

(boolean_expression) ? code1 : code2;

If boolean_expression returns true, the code1 will be executed;


If boolean_expression returns false, the code2 will be executed.

Example 4.5
$score = 100;
$result = ($score >= 60 )? "passed" : "failed";
print "The examination is $result";
Output:
The examination is passed
Explanation:
Because ($score >= 60 ) returns true, “passed” has been executed.
The value of $result is passed.
While Loop

while(condition){
code;
}
The loop is executed when the condition is true, and exits when the condition
is false
Example 4.6
$num = 1;
while( $num <= 8 ){ # run 8 times
print "$num ";
$num = $num + 1;
}
Output:
1 2 3 4 5 6 7 8
Explanation:
“while( $num <= 8 )” checks whether the condition is true, if the condition is
false, the program exits the loop.
Do…While Loop

do{
code;
} while( condition );

Run the code first, then check whether the condition is true.
The loop is executed when the condition is true, and exits when the condition
is false.
Example 4.7
$num = 1;
do{
print "$num ";
$num = $num + 1;
} while( $num <= 8 ) # run 8 times
Output:
1 2 3 4 5 6 7 8
Explanation: Run the code within the do loop first, then:
“while( $num <= 8 )” checks whether the condition is true, if the condition is
false, the program exits the loop.
Until Loop

until(condition){
code;
}

The loop is executed when the condition is false, and exits when the
condition is true.
Example 4.8
$num = 1;
until( $num > 8 ){ # run 8 times
print "$num ";
$num = $num + 1;
}
Output:
1 2 3 4 5 6 7 8
Explanation:
Because until( $num > 8 ) returns false, the code within the until loop has
been executed for 8 times, until the condition is true.
For Loop

for ( init; condition; increment ){


code;
}

The loop is executed when the condition is true, and exits when the condition
is false
Example 4.9
for( $num = 1; $num <= 8; $num++ ){
print "$num ";
}
Output:
12345678
Explanation:
“$num = 1” sets up the initial value.
“$num <= 8” sets up the condition of the loop.
“$num++” sets up the increment of each loop.
“for(…)” keeps looping until the condition is false.
Foreach Loop

foreach variable (list) {


code
}
“foreach loop” is used to iterate through all variable values in a collection.
Example 4.10
@myArray = (1, 6, 9, 8);
foreach $var (@myArray){
print "$var ";
}
Output:
1698
Explanation:
“foreach” statement iterates through all elements in the @myArray, assigns
the values to the $var, and outputs its all values.
Continue

while(condition){
code1;
}continue{
code2;
}

The continue statement is used to continue next loop.


Example 4.11

$num = 10;
while($num <= 15){
print "$num ";
} continue {
$num = $num + 1;
}

Output:
10 11 12 13 14 15
Explanation:
“continue{ $num = $num + 1;}” continues running next while loop after the
current block.
Last

last;
The last statement is used to exit the loop block, end the loop.

Example 4.12
$num = 10;
while( $num < 18 ){
if( $num == 15){ last; }
$num++;
print "$num ";
}
Output:
11 12 13 14 15
Explanation:
“if( $num == 15){ last; }” exits the loop block when $num is 15.
Hour 5
Local & Greenwich Time

localtime() # returns a local time


gmtime() # returns a Greenwich time
time() # returns the seconds accumulated since 1/1/1970

Example 5.1

$local_time = localtime();
print "The local time is:$local_time\n";
$grw_time = gmtime();
print "The Greenwich time is:$grw_time\n";
$epoc = time();
print "The cumulative seconds since 1/1/1970 is:$epoc\n";

Output:
The local time is:Tue Oct 13 15:11:30 2020
The Greenwich time is:Tue Oct 13 19:11:30 2020
The cumulative seconds since 1/1/1970 is:1602618009
Explanation:
localtime() returns a local time, gmtime() returns a Greenwich time, time()
returns the seconds accumulated since 1/1/1970.
Subprogram
Subprogram is a function in Perl, it can be used repeatedly.
1. The syntax to define a subprogram is:

sub subName{ # subprogram is a function in Perl


}

2. The syntax to call a function is:

subName();

Example 5.2

sub book{ # define a subprogram


print "Scala in 8 Hours!";
}
book(); # call the subprogram

Output:
Scala in 8 Hours!
Explanation:
“sub book{…}” defines a subprogram “book”.
“book()” calls the subprogram “book”.
Subprogram With Parameters
1. The syntax to define a subprogram is:
sub subName{
code @_ # @_ accepts all come-in parameters
}

@_[0] represents the number 0 parameter.


@_[1] represents the number 1 parameter.
@_[2] represents the number 2 parameter.

2. The syntax to call a function is:

subName(parameters);

Example 5.3
sub books{
print "All books are : @_ \n";
print "$_[0] in 8 Hours\n";
print "$_[1] in 8 Hours\n";
print "$_[2] in 8 Hours\n";
}
books("C#", "GO", "VB");

Output:
All books are : C# GO VB
C# in 8 Hours
GO in 8 Hours
VB in 8 Hours

Explanation:
Subprogram is a function in Perl.
“books("C#", "GO", "VB");” calls the subprogram “books” with parameters
“C#, GO, VB”
“@_” represents all come-in parameters.
@_[0] represents the number 0 parameter C#.
@_[1] represents the number 1 parameter GO.
@_[2] represents the number 2 parameter VB.
Return

“return” command is used to return its value to the caller.

return

Example 5.4
sub addition{
$sum = $_[0]+$_[1];
return $sum; # return its value to the caller
}
print addition(10, 20) # caller

Output:
30
Explanation:
“return $sum” returns its value to the caller “addition(…)”, just like
“addition(10, 20) = $sum;”
Public & Private Variable

The variable defined outside a working scope is a public variable.


The variable defined inside a working scope is a private variable.
Working scope means a {…} range of a function, if, while, for, foreach. A
private variable is invisible outside the working scope.

my $variable # “my” defines a private variable

Example 5.5

$var = "Public String"; # define a public variable


sub show{
my $var = "Private String"; # define a private variable
print "$var\n"; # print private variable
}
print "$var\n"; # print public variable
show();

Output: Public String


Private String
Explanation:
$var = "Public String" is a public variable outside “sub show{}”
my $var = "Private String" is a private variable in “sub show{}”
Static Variable
Static variable makes its value last. Once a static variable is assigned a value,
its value will persist until this static variable is given a new value.

use feature 'state'; # import ‘state’ before using static


state $variable; # define a static variable

Example 5.6

use feature 'state'; # import ‘state’ feature


sub show{
state $number; # define a static variable
$number++;
print "$number ";
}
for (0..7){ show(); } # call show() 7 times

Output: 1 2 3 4 5 6 7 8
Explanation:
“state $number;” defines a static variable, its value will last until being
updated.
Reference
The reference is a pointer, which points to a variable, array, hash,
subprogram. The value of a reference is a memory address.
By using a “\”, we can create a reference like this:
$var = \$variable; # variable reference
$arr = \@array; # array reference
$ha = \%hash; # hash reference
$sub = \&subprogram; # subprogram reference

Example 5.7

$var = "ok";
$v = \$var; # reference
print "$v\n";
@arr = (10, 20, 30);
$a = \@arr; # reference
print "$a\n";

Output: SCALAR(0x55f27b7c29f8)
ARRAY(0x55f27b7c2ab8)
Explanation:
“$v = \$var;” defines a variable reference.
“$a = \@arr;” defines an array reference.
Cancel Reference
By adding a symbol $, @, %, & before a reference, we can cancel the
reference.
$$var # cancel reference
@$arr # cancel reference
%$ha # cancel reference
&$sub # cancel reference

Example 5.8

$var = "ok";
$v = \$var;
print "$$v\n"; # cancel reference
@arr = (10, 20, 30);
$a = \@arr;
print "@$a\n"; # cancel reference

Output: ok
10 20 30
Explanation:
"$$v\n" cancels reference by adding a $ before the reference.
"@$a\n" cancels reference by adding a @ before the reference.
Format Output (1)
We can use “format” to format the contents, and use “write” to output the
formatted contents.
The syntax to define a format contents is as follows:
format STDOUT =
# define a format contents
.

The syntax to output a formatted contents is as follows:


write; # output the formatted contents

Example 5.9
format STDOUT =
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"In 8 Hours" Programming
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.

write;

Output:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"In 8 Hours" Programming
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Explanation:
“format STDOUT = .” defines a format contents.
“write;” outputs the formatted contents.
Format Output (2)
We can use “format” to format the contents, and use “write” to output the
formatted contents.
The syntax to define a format contents is as follows:
format myFormat =
# define a format contents named “myFormat”
.

The syntax to output a formatted contents is as follows:


$~ = "myFormat"; # reference the myFormat
write; # output the contents of $~

Example 5.10
format myFormat =
**********************************
"In 8 Hours" Series Books
**********************************
.
$~ = "myFormat";
write;

Output:
**********************************
"In 8 Hours" Series Books
**********************************

Explanation:
“format myFormat = .” defines a format content.
“myFormat” is a name of the format contents.
“$~ = "myFormat";” specifies the format contents to be used.
“write;” outputs the formatted contents.
Hour 6
Open a File
The syntax to open a file is as follows:
open( DATA, ‘mode’, ‘myfile.txt’) or die $!;
“DATA” is the file handle, which is used for I/O connection.
“mode” is a command to open a file in a specified way.
“die $!” shows a warning if fail to process the file.

The mode to open a file is as follows:


Mode Description
< or r read only
> or w write only
>> or a append
+< or r+ read or write
+> or w+ write or read
+>> or a+ append (write or read)

For example:
“open(DATA, ‘ < ’, ‘myfile.txt’) or die $!;” means that open the
“myfile.txt” in read-only mode.
Write to File
The syntax to write to file is as follows:
print DATA $contents;
“$contents” is something that needs to write to a file.
Example 6.1
my $str = "Rust in 8 Hours"; # the contents to write
my $f = 'C:\myPerl\myfile.txt'; # the path to write
open(DATA, '>', $f) or die $!;
print DATA $str; # write the contents to myfile.txt
close(DATA); # close the file
print "Write to myfile.txt successfully!\n";
Output:
Write to myfile.txt successfully!
Explanation:
Please check ‘'C:\myPerl\myfile.txt'’, you can find the contents “Rust in 8
Hours” in myfile.txt.
“print DATA $str;” writes the contents to myfile.txt.
Read from File
The syntax to read contents from a file is as follows:
while(<DATA>){
print $_;
}
“$_” represents all contents in the file.
Example 6.2
my $f = 'C:\myPerl\myfile.txt'; # the path & file to read
open(DATA, '<', $f) or die $!;
while(<DATA>){
print $_; # read all contents from myfile.txt
}
print "\nRead a file successfully!";
close(DATA); # close the file

Output:
Rust in 8 Hours
Read a file successfully!
Explanation:
“while(<DATA>){ print $_; }” reads contents from myfile.txt.
Input by User
The syntax to input data from a user to a file is as follows:
$data = <STDIN>;

Example 6.3
print "What is your name?\n";
$data = <STDIN>;
print "My name is: $data\n";

Output:
What is your name?
Ray Yao
My name is: Ray Yao
Explanation:
“$data = <STDIN>;” is used to input data by users.
STDIN, STDOUT, and STDERR represent standard input, standard output,
and standard error respectively.
File Copy
The syntax to copy a file is as follows:

while(<DATA1>){ # copy data1 to data2


print DATA2 $_;
}

Example 6.4

open(DATA1, '<', 'C:\myPerl\myfile.txt'); # open an old file


open(DATA2, '>', 'C:\myPerl\ourfile.txt'); # open a new file
while(<DATA1>){ # copy
print DATA2 $_;
}
print "Copy a file successfully!";
close( DATA1 );
close( DATA2 );

Output:
Copy a file successfully!
Explanation:
Please check 'C:\myPerl\ourfile.txt'.
DATA1 represents file1, DATA2 represents file2.
File Rename
The syntax to rename a file is as follows:

rename ( file1, file2 );


Change the name of file1 to file2.

Example 6.5
my $file1 = 'C:\myPerl\myfile.txt';
my $file2 = 'C:\myPerl\yourfile.txt';
rename ( $file1, $file2 );
print "Rename a file successfully!";

Output:
Rename a file successfully!
Explanation:
Please check 'C:\myPerl\yourfile.txt'.
“rename ( $file1, $file2 );” rename the “myfile.txt” as “yourfile.txt”.
File Remove
The syntax to remove a file is as follows:

unlink ( file );

Example 6.6
my $file = 'C:\myPerl\ourfile.txt';
unlink ( $file );
print "Remove a file successfully!";

Output:
Remove a file successfully!

Explanation:
Please check 'C:\myPerl\ourfile.txt', which is no longer existing.
“unlink ( $file );” removes the “ourfile.txt”.
File Information
“_ _” can return the information of a file.
_ _FILE_ _ returns the current file name
_ _PACKAGE_ _ returns the package name of the file
Note: “_ _” is two underlines.

Example 6.7
print "The file name is : " . __FILE__ . "\n";
print "The package name is : " . __PACKAGE__ . "\n";
Please save this file and its name as “myScript.pl”
Output:
The file name is : myScript.pl
The package name is : main
Explanation:
_ _FILE_ _ returns the current file name.
_ _PACKAGE_ _ returns the package name of the current file.
Directory Operation
The standard commands to process a directory is as follows:
Commands Operations
opendir open a dirctory
readdir read a directroy
mkdir create a directory
chdir specify a current directory
rmdir remove a directory
telldir return the position of the current directory
seekdir return the position of the specified directory
closedir close a directory
Create a Directory
The syntax to create a directory is as follows:
mkdir( “ path / directory ”);
Create a new directory under the specified path.
Example 6.8
$d1 = "/myPerl/Directory1";
$d2 = "/myPerl/Directory2";
mkdir( $d1 ) or die "$!";
mkdir( $d2 ) or die "$!";
print "Create two directories successfully!\n";
Output:
Create two directories successfully!
Explanation:
Please check the directories “C:\myPerl”, you will find that two new
directories “Directory1” and “Directory2” have been created.
“mkdir( $d1 )” creates a “Directory1” under “C:\myPerl”.
“mkdir( $d2 )” creates a “Directory2” under “C:\myPerl”.
Open & Read a Directory
The syntax to open or read a directory is as follows:
opendir (DIR, ‘ \directory ’); # open a directory
read DIR # read the directory

Example 6.9
opendir (DIR, 'C:\myPerl') or die $!;
while ($contents = readdir DIR) {
print "$contents\n"; # show anything under \myPerl
}
closedir DIR;
Output:
Directory1
Directory2
……
Explanation:
“opendir (DIR, 'C:\myPerl')” opens the directory “\myPerl”.
“readdir DIR” reads the directory “\myPerl”.
Change & Remove a Directory
The syntax to change or remove a directory is as follows:
chdir( ‘\directory’ ); # change as the current directory
rmdir( ‘\directory’ ); # remove the specified directory

Example 6.10

$d1 = "/myPerl/Directory1";
chdir( $d1 ) or die \$!; # specify the current directory
print "The directory you are in is $d1\n";
$d2 = "/myPerl/Directory2";
rmdir( $d2 ) or die $!; # remove the specified directory
print "Remove Directory2 successfully!\n";

Output:
The directory you are in is /myPerl/Directory1.
Remove Directory2 successfully!
Explanation:
“chdir( $d1 )” specifies Directory1 as the current directory.
“rmdir( $d2 )” removes Directory2.
Please check “C:\myPerl”, you cannot find Directory2 now.
Hour 7
Die Function
When an error happens, “die function” stops the running program, and
outputs the error messages.

die “ error message ”, $!;

Example 7.1
open(DATA,"<", abc.txt)
or die "Error! Cannot open abc.txt! \n", $!;
# assume that there is no abc.txt
# in the current directory.
close(DATA);
Please Save the file as “test01.pl” in “C:\myPerl”, and run it.
Output:
Error! Cannot open abc.txt!
No such file or directory at test01.pl line 1.
Explanation:
Because there is no “abc.txt” in the current directory, “die()” stopped the
running program, and outputs the error message.
Warn Function
When an error happens, “warn function” outputs the warning messages.

warn " warning message ";

Example 7.2
open(DATA,"<", abc.txt)
or warn "Warning: Cannot open abc.txt!";
# assume that there is no abc.txt
# in the current directory.
close(DATA);
Please Save the file as “test02.pl” in “C:\myPerl”, and run it.
Output:
Warning: Cannot open abc.txt! at test02.pl line 1.
Explanation:
Because there is no “abc.txt” in the current directory, “warn()” outputs the
warning message.
Sysopen Function
Sysopen function is used to open a file in different modes.
The syntax of sysopen() is:
sysopen( DATA, "file.txt", mode );

The usage of the parameter “mode” is as follows:


Modes Open the file for this purpose:
O_RDWR read or write
O_RDONLY read only
O_WRONLY write only
O_CREAT create a file
O_APPEND append a file
O_EXCL check whether the file exists

For example:
sysopen(DATA, "myfile.txt", O_WRONLY);
# open a file “myfile.txt”, for writing only.
Match Operator
Match operator is used to check if a string contains a substring.

=~ /…/ # check whether some characters match


!~ /.../ # check whether no characters match

Example 7.3

$book = "Kotlin in 8 Hours";


if ( $book =~ /8 Hours/ ){ # check match
print "Some words match '8 Hours' \n";
}
if ( $book !~ /8 Hours/ ){ # check doesn’t match
print "No words match '8 Hours' \n";
}

Output:
Some words match '8 Hours'
Explanation:
“$book =~ /8 Hours/” checks whether some words in the $book match “8
Hours”.
“$book !~ /8 Hours/” checks whether no words in $book match “8 Hours”
RegExp Variable
There are three RegExp variables that can match different strings.

$` # gets the previous substring of the matching string


$& # gets the matching string
$' # gets the following substring of the matching string
Note: The symbol of $` is different from $'
Example 7.4
$str = "HTML CSS in 8 Hours";
$str =~ /CSS/;
print "The previous string: $`\n";
print "The matching string: $&\n";
print "The following string: $'\n";

Output:
The previous string: HTML
The matching string: CSS
The following string: in 8 Hours
Explanation: $`, $&, $' return the previous string, the matching string,
and the following string respectively.
Substitute Operator
The syntax to substitute a string1 as a string2 is as follows:

=~ s / string1 / string2 /;

“s” is a substitute operator parameter.

Example 7.5
$str = "Visual C# in 8 Hours";
$str =~ s/C#/Basic/; # substitution
print "$str\n";

Output:
Visual Basic in 8 Hours
Explanation:
“=~ s / C# / Basic /;” substitutes the substring1 “C#” as the substring2
“Basic”.
Lowercase & Uppercase Convert
The syntax to convert lowercase and uppercase is as follows:

=~ tr / A-Z / a-z /; # convert to lowercase


=~ tr / a-z / A-Z /; # convert to uppercase

Example 7.6

$str1 = 'Shell Scripting in 8 Hours';


$str1 =~ tr/A-Z/a-z/;
print "$str1\n";
$str2 = 'Shell Scripting in 8 Hours';
$str2 =~ tr/a-z/A-Z/;
print "$str2\n";

Output:
shell scripting in 8 hours
SHELL SCRIPTING IN 8 HOURS
Explanation:
“$str1=~ tr/A-Z/a-z/;” converts the str1 to lowercase.
“$str2=~ tr/A-Z/a-z/;” converts the str2 to uppercase.
Remove Double Character
The words with double characters are like these: good, leek, see, woo,
vacuum, ……
The syntax to remove one of the double characters is:
=~ tr /a-z / a-z /s;
“/s” converts the double characters to a single character.

Example 7.7
$str = 'I see a bee over the book';
$str =~ tr/a-z/a-z/s; # remove a double character
print "$str\n";
Output:
I se a be over the bok
Explanation:
“=~ tr/a-z/a-z/s;” removes one of the double characters. Therefore, the “see”
becomes “se”, the “bee” becomes “be”, the “book” becomes “bok”.
Delete Specified Characters
The syntax to delete the specified characters is:

=~ tr /character / /d;
“/d” deletes the specified characters.

Example 7.8
$str = 'HTML CSS in 8 Hours';
$str =~ tr/CSS/ /d; # delete CSS
print "$str\n";

Output:
HTML in 8 Hours

Explanation:
“=~ tr/CSS/ /d;” deletes the specified characters “CSS” in the string.
Default Variable
When no any variable is defined explicitly, $_ is a default variable which
contains all input values.
Therefore, $_ is a special default variable in Perl.

Example 7.9
foreach ('JAVE','HTML','PERL') {
print $_; # $_ represents all element values
print " ";
}

Output:
JAVE HTML PERL

Explanation:
In the above program, no any variable is defined explicitly, $_ is a default
variable that contains all values “JAVA, HTML, PERL”.
Show the Perl comments
“__DATA__” is a parameter to make the comments to be shown.
The syntax to show the Perl comments is as follows:
while(<DATA>){ print $_; }
__DATA__

Example 7.10
while(<DATA>){
print $_;
}
__DATA__ # make the following comments shown

=pod
=head1
This is a pod document, which is used as a Perl comment.
=head2
Perl usually ignores the comment, but now I will be shown.
=cut

# I am a Perl comment
# This comment will be shown by __DATA__
Output:
=pod
=head1
This is a pod document, which is used as a Perl comment .
=head2
Perl usually ignores the comment, but now I will be shown .
=cut

# I am a Perl comment
# This comment will be shown by __DATA__

Explanation:
“__DATA__” is a parameter to make the comments to be shown.
The following is a pod document, which work as a comment.
The structure of a pod document is as follows:
=pod
=head1
…....
=head2
……
=head3
……
=cut
Hour 8
Class & Object

Class
Class is the general name for all things related, is a template of an object.
In Perl, a class is just a simple package, we can use a package as a class. The
syntax to create a class is as follows:
package MyClass;

Object
Object is an instance of a class. We can create an object of a class. The syntax
to create an object is as follows:
new MyClass( parameters);

Constructor
Constructor is used to initialize the properties of the class.
The syntax to create a constructor is as follows:
sub new {……}
Constructor
When creating an object, we need a constructor to initialize.
In Perl the structure of the constructor is a little complicated, so we need to
study it in detail.
The structure of the constructor is as follows:

sub new {
my $class = shift; # “shift” accepts all come-in parameters
my $self = { key => shift }; # { key => shift } is a hash
bless $self, $class; # “bless” relates two parameters
return $self; # “self” represents the instance of the class.
}

Explanation:
“sub new{…}” create a constructor.
“$class = shift;” accepts all come-in parameters when creating an object.
“shift” is a keyword which is used to process multi parameters.
{ key => shift } is a hash which assigns a value to a key.
“bless” is a keyword which is used to relate two parameters.
“return $self” returns a reference to the object.
Class & Object Example

Example 8.1
package Student; # create a class
sub new{ # create a constructor
my $class = shift;
my $self = {
username => shift,
surname => shift,
number => shift,
};
print "Username:$self -> {username}\n";
print "Surname:$self -> {surname}\n";
print "Number:$self -> {number}\n";
bless $self, $class;
return $self;
}
new Student(" Ann", " Rose", " 1688"); # create an object
Output:
Username: Ann
Surname: Rose
Number: 1688
Explanation:
“package Student;” creates a class.
“sub new{……}” creates a constructor.
“shift” is a keyword which is used to process multi parameters.
“$self” keyword represents the instance of the class.
“bless $self, $class;” relates two parameters “$self” & “$class”.
“return $self;” returns the reference to object.
“new Student(" Ann", " Rose", " 1688");” creates an object and passes three
parameters to the constructor.
Define a Method
The syntax to define a method is as follows:

sub myMethod {
my ( $self, $variable) = @_;
return $self -> {$variable};
}
Note: The first parameter should be a “$self” in Perl method.
“@_” accepts all come-in parameters
“return $self -> {$variable};” returns the value to the caller.

Example 8.2

package Student; # create a class


sub new{ # create a constructor
my $class = shift;
my $self = {
username => shift,
surname => shift,
number => shift,
};
print "Username:$self -> {username}\n";
print "Surname:$self -> {surname}\n";
print "Number:$self -> {number}\n";
bless $self, $class;
return $self;
}
sub getUserName { # define a method
my ( $self, $username ) = @_; # @_ accepts parameters
return $self -> {username}; # returns value to the caller
}
1; # The “1” indicates that the file is loaded successfully
$object = new Student(" Ann", " Rose", " 1688");
# create an object
$username = $object -> getUserName(); # call the method
print "The student username is : $username\n";
Output:
Username:Ann
Surname: Rose
Number: 1688
The student username is : Ann
Explanation:
“sub getUserName {……}” defines a method “getUserName”
“@_” accepts all come-in parameters.
“return $self -> {username};” returns the value to the caller
“$object = new Student(……");” creates an object.
“$object -> getUserName();” calls the method “getUserName”.
Inheritance
A child class can inherit the feature of the parent class.
The syntax of the inheritance is as follows:
package ChildClass; # create a child class
our @ISA = ParentClass; # inherit a parent class

Example 8.3

package Student; # create a class


sub new{ # create a constructor
my $class = shift;
my $self = {
username => shift,
surname => shift,
number => shift,
};
print "Username:$self -> {username}\n";
print "Surname:$self -> {surname}\n";
print "Number:$self -> {number}\n";
bless $self, $class;
return $self;
}

# define a method
sub getUserName {
my ( $self, $username ) = @_;
return $self -> {username};
}
1;

$object = new Student(" Ann", " Rose", " 1688");


# create an object
$username = $object -> getUserName(); # call the method
print "The student username is : $username\n";

package Pupil; # create a child class “Pupil”


our @ISA = Student; # inherit the parent class “Student”
$object = new Pupil( " Tom", " Watt", " 1689");
$username = $object -> getUserName();
print "The pupil username is : $username\n";

Output:
Username : Ann
Surname : Rose
Number : 1688
The student username is : Ann
Username : Tom
Surname : Watt
Number : 1689
The pupil username is : Tom
Explanation:
“package Pupil;” creates a child class “Pupil”
“our @ISA = Student;” inherits a the parent class “Student”.
Package
A package is equal to a class. The default package name is “main” package,
but we can create a new package.

package myPack; # create a new package


__PACKAGE__ # get the name of the package

Example 8.4

# in the default package


print "The Package Name : " , __PACKAGE__ , "\n";
package ipack; # create a new package “ipack”
print "The Package Name : " , __PACKAGE__ , "\n";
package main; # return the main package
print "The Package Name : " , __PACKAGE__ , "\n";
1;

Output:
The Package Name : main
The Package Name : ipack
The Package Name : main
Explanation: __PACKAGE__ gets the name of the package
BEGIN & END Modules
BEGIN{…} # execute before any other statements
END{…} # execute after any other statements.

Example 8.5

package myPack;
print "Note the sequence of statement running\n";
BEGIN {
print "Run the GEGIN module first.\n"
}
END {
print "Run the END module last.\n"
}
1;

Output:
Run the GEGIN module first.
Note the sequence of statement running
Run the END module last.
Explanation:
“BEGIN{…}” is the first statement to run.
“END{…}” is the last statement to run.
Module
A Perl module is a reusable package, the module name is the same as the
package name.
The syntax to create a module is as follows:
package MyModule;
The module will be referenced by another file.
The extension name of the module is “.pm”

Example 8.6
package MyModule; # create a module
sub func{
print "I am MyModule.pm\n";
print "I am called by main.pl\n";
}
1;
Please save the module as “MyModule.pm” at C:\myPerl.
“package MyModule;” creates a module “MyModule.pm”;
This module will be referenced by another Perl file.
Require
“require” command is used to import a module. Its syntax is:
require “ path/module.pm ”; # import a module

module :: function(); # call the module’s function

Example 8.7

require "C:/myPerl/MyModule.pm"; # import the module


MyModule::func(); # call the function in the module
print "I am main.pl\n";
print "I am calling func in MyModule";

Please save the file as “main.pl” at C:\myPerl, and run it.


Output:
I am MyModule . pm
I am called by main . pl
I am main . pl
I am calling func in MyModule
Explanation:
‘require "C:/myPerl/MyModule.pm";’ imports a module.
‘MyModule::func();’ calls func() in MyModule.pm.
Appendix
Perl Q & A
Questions:

Please fill in the correct answers.

01.
print "Hello!"; # single-line comment
=fill in
multi-line comment
multi-line comment
multi-line comment
=cut
A. block B. comment C. module D. pod

02.
fill in constant MON => "Monday"; # define a constant
fill in constant SUN => "Sunday";
print MON ."\n";
print SUN ."\n";
A. public B. private C. use D. dim

03.
fill inscore = ('60'=>'passed', '85'=>'ok', '100'=>'excellent');
print "$score{'60'}\n";
print "$score{'85'}\n";
print "$score{'100'}\n";
A. $ B. % C.@ C.&

04.
fill in(boolean_expression){
# execute when boolean_expression returns false
}
A. except B. if not C. unless D. if
05.
localtime() # returns a local time
fill in() # returns a Greenwich time
time() # returns the seconds accumulated since 1/1/1970
A. Greenwich B. GreenwichTime C. gntime D. gmtime

06.
“open(DATA, ‘ +>> ’, ‘myfile.txt’) or die $!;” means
A. open the “myfile.txt” in append mode.
B. open the “myfile.txt” in read-only mode.
C. open the “myfile.txt” in write-only mode.
D. open the “myfile.txt” in read & write mode.

07.
die “ error message ”, fill in;
# show error message from Perl

A. $_ B. $! C. $$ D. $*

08.
fill in MyClass;
# create a class

A. class B. new C. create D. package

09.
fill in "Here"; # define a Here Document
……
Here
A. <= B. => C. << D. >>
10.
Which following statement can create an array?
A. &arrayName = [val1, val2, val3];
B. @arrayName = [val1, val2, val3];
C. &arrayName = (val1, val2, val3);
D. @arrayName = (val1, val2, val3);

11.
Which following statement can create a hash?
A. &hash = ('key1'=>'val1', 'key2'=>'val2', 'key3'=>'val3',...);
B. %hash = ('key1'=>'val1', 'key2'=>'val2', 'key3'=>'val3',...);
C. &hash = ['key1'=>'val1', 'key2'=>'val2', 'key3'=>'val3',...];
D. %hash = ['key1'=>'val1', 'key2'=>'val2', 'key3'=>'val3',...];

12.
fill in(condition){
code;
}
# The loop is executed when the condition is false, and exits the loop when
the condition is true.
A. until B. switch C. while D. do

13.
sub subName{
code fill in ; # accepts all come-in parameters
}
A. &_ B. $_ C. %_ D. @_

14.
my $f = 'C:\myPerl\myfile.txt'; # the path & file to read
open(DATA, '<', $f) or die $!;
while(<DATA>){
print fill in ; # read all contents from myfile.txt
}
print "\nRead a file successfully!";
close(DATA); # close the file
A. &_ B. $_ C. %_ D. @_

15.
“sysopen(DATA, "myfile.txt", O_EXCL);” means
A. open a file “myfile.txt”, for read only.
B. open a file “myfile.txt”, for writing only.
C. open a file “myfile.txt”, for append only.
D. open a file “myfile.txt”, check whether the file exists.

16.
The syntax of the inheritance is as follows:
package ChildClass; # create a child class
our fill in = ParentClass; # inherit a parent class

A. @ASI B. @IAS C. @ISA D. @SIA

17.
$score = 100; # $score is a variable
print "$score \n"; # using double quotes
print '$score \n'; # using single quotes
What is the outup?
A. 100
B. 0
C. nothing
D. $score \n

18.
$myStr = "Hello My Friends"; # create a string
@arr = split(' ', $myStr); # convert to array
$str = fill in( '**', @arr ); # convert to string
print "$arr[0] $arr[1] $arr[2] \n";
print "$str\n";
A. convert B. join C. string D. str

19.
%score = ('60'=>'passed', '85'=>'ok', '100'=>'excellent');
@arr = fill in %score; # get all element values of the hash
print "$arr[0]\n";
print "$arr[1]\n";
print "$arr[2]\n";
A. values B. elements C. hash D. %

20.
$num = 10;
while( $num < 18 ){
if( $num == 15){ fill in; } # exit the loop block, end the loop
$num++;
print "$num ";
}
A. first B. exit C. break D. last

21.
$var = "Public String"; # define a public variable
sub show{
fill in $var = "Private String"; # define a private variable
print "$var\n"; # print private variable
}
print "$var\n"; # print public variable
show();
A. private B. priv C. my D. state
22.
my $file = 'C:\myPerl\ourfile.txt';
fill in ( $file ); # remove the file
print "Remove a file successfully!";
A. remove B. delete C. eradicate D. unlink

23.
while(<DATA>){
print $_;
}
fill in # make the following comments shown

=pod
=head1
This is a pod document, which is used as a Perl comment.
=head2
Perl usually ignores the comment, but now I will be shown.
=cut

# I am a Perl comment
# This comment will be shown

A. __PACKAGE__
B. __DATA__
C. __FILE__
D. __COMMENT__

24.
fill in "C:/myPerl/MyModule.pm"; # import the module
MyModule::func(); # call the function in the module
print "I am main.pl\n";
print "I am calling func in MyModule";
A. import B. include C. reference D. require
Answers:

01. D 09. C 17. D


02. C. 10. D 18. B
03. B 11. B 19. A
04. C 12. A 20. D
05. D 13. D 21. C
06. A 14. B 22. D
07. B 15. D 23. B
08. D 16. C 24. D

The source code download link:


https://forms.aweber.com/form/04/1810519104.htm
Source Code Download
Angularjs in 8 Hours
C# in 8 Hours
C++ in 8 Hours
Django in 8 Hours
Go in 8 Hours
Html Css in 8 Hours
Java in 8 Hours
JavaScript in 8 Hours
JQuery in 8 Hours
Kotlin in 8 Hours
MySql in 8 Hours
Node.Js in 8 Hours
Perl in 8 Hours
Php MySql in 8 Hours
PowerShell in 8 Hours
Python in 8 Hours
R in 8 Hours
Ruby in 8 Hours
Rust in 8 Hours
Scala in 8 Hours
Shell Scripting in 8 Hours
Swift in 8 Hours
Visual Basic in 8 Hours
Xml Json in 8 Hours

Source Code Download Link:


https://forms.aweber.com/form/04/1810519104.htm

You might also like