PERL in 8 Hours, For Beginners, Learn Coding Fast! - Perl Programming (BooksRack - Net)
PERL in 8 Hours, For Beginners, Learn Coding Fast! - Perl Programming (BooksRack - Net)
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
Note:
This book is only for Perl beginners, it is not suitable for experienced Perl
programmers.
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
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.
3. Open the Notepad, input the following Perl code to the Notepad editor.
#
# is used to single-line comment.
=pod
……
……
=cut
“=pod……=cut” is used to multi-line comment.
Example 1.1
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
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 ‘……’
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.
$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;
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)
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);
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");
pop(@array);
Example 2.8
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:
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.
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
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
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:
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
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
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
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
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
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";
}
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";
}
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
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
while(condition){
code1;
}continue{
code2;
}
$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
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:
subName();
Example 5.2
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
}
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
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
Example 5.5
Example 5.6
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
.
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”
.
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.
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:
Example 6.4
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:
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.
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.
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 );
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.
Example 7.3
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.
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 /;
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:
Example 7.6
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
Example 8.3
# define a method
sub getUserName {
my ( $self, $username ) = @_;
return $self -> {username};
}
1;
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.
Example 8.4
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
Example 8.7
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
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
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: