Perl Programming - 01 Basic Perl

Preview:

Citation preview

Perl Programming

1

Danairat T.

Line ID: Danairat

FB: Danairat Thanabodithammachari

+668-1559-1446

Danairat T.

Contents

Module-1: Introduction to Perl Programming

• Basic Variables; string, number, array, hash

• Basic Program Flows; if, unless

• Basic Program Loops; while, for, for each, do,

until

2

Danairat T.

Contents

Module-2: Regular Expression

• Introduction to Regular Expression

• Matching pattern

• Special characters handling

• Substitute

• Global substitutions

3

Danairat T.

Contents

Module-3: File Handling

• Open file for Read or Write

• Close file handle

• File handle Manipulation

• Using regular expression in file handling

4

Danairat T.

Contents

Module-4: Connecting to Database

• Understand Perl built-in associate array file

• Using module Perl DBI

• Connection to MySQL or Oracle database

• Insert/Update/Delete/Select by Perl

5

Perl Programming

01 - Introduction to Perl Programming

6

Danairat T.

Line ID: Danairat

FB: Danairat Thanabodithammachari

+668-1559-1446

Danairat T.

What is Perl?(Practical Extraction and Report Language )

• Perl, release in 1987, is a high-level programming language written by Larry Wall. Perl's process, file, and text manipulation facilities make it particularly well-suited for tasks system utilities, system management tasks, database access, networking. These strengths make it especially popular with system administrators.

7

Danairat T.

Which version of Perl should I use?

• No one is actively supporting Perl 4. Five years ago it

was a dead camel carcass

• There is no Perl 6 release scheduled.

• The immediate releases are Perl 5.8 (i.e. Perl5.8.x )

8

Danairat T.

OS Platforms Support

• UNIX: More or less every UNIX or UNIX-like operating system ever created, notably

Linux , Solaris, AIX, IRIX, HP/UX, BSD, and Tru64

• MS Windows: DOS, Windows 3.1, 95, 98, NT and 2000

• Other Desktop OSs: Apple Macintosh (68k and PPC, both pre and post MacOS X),

Acorn Risc OS, Amiga, BeOS, OS/2, and many others

• Mainframes: AS/400, OS390, VMS and OpenVMS, Stratus (VOS), and Tandem

• PDAs: EPOC (Psion/Symbian), but not PalmOS or Windows CE at time of writing,

although porting efforts are being made for both platforms

9

Danairat T.

Identify the Perl version

• perl –v

• perl -V

10

Danairat T.

www.CPAN.org

• CPAN stands for

Comprehensive Perl

Archive Network,

containing libraries,

documentation, and many

Perl third-party modules

and extensions

11

Danairat T.

Install Perl

• On Unix System– pkgadd -d /cdrom/sol_10_1009_x86/Solaris_10/Product SUNWperl584core

– pkgadd –d /cdrom/sol_10_1009_x86/Solaris_10/Product SUNWperl584usr

– pkgadd –d /cdrom/sol_10_1009_x86/Solaris_10/Product SUNWperl584man

• On Windows System– run ActivePerl-5.8.9.826-MSWin32-x86-290470.msi

Available for download at www.activestate.com

12

Danairat T.

Perl file structure and location

• Perl executable: /usr/perl5/bin/perl or /usr/bin/perl

• Perl Pain Old Documentation: /usr/perl5/pod

• Perl Manual: /usr/perl5/man

13

Danairat T.

Perl Libraries (Perl Modules)

• The Perl Libraries directories

– /usr/perl5/5.8.4/lib/i86pc-solaris-64int

– /usr/perl5/5.8.4/lib

– /usr/perl5/site_perl/5.8.4/i86pc-solaris-64int

– /usr/perl5/site_perl/5.8.4

– /usr/perl5/site_perl

– /usr/perl5/vendor_perl/5.8.4/i86pc-solaris-64int

– /usr/perl5/vendor_perl/5.8.4

– /usr/perl5/vendor_perl

14

Danairat T.

Perl Library (The modules for Unix)

http://www.cpan.org/modules/01modules.index.html

15

Danairat T.

Perl Library (PPM modules for windows)http://ppm.activestate.com/PPMPackages/zips/8xx-builds-only/Windows/

16

Danairat T.

Install Perl Modules on Unix

gzip -dc yourmodule.tar.gz | tar -xof -

cd /your/new/lib/to/install/

perl Makefile.PL

make

make test

make install

Or, if you have internet access

perl -MCPAN -e shell

cpan> i /Time/

cpan> install Time::CTime

17

Danairat T.

Install Perl Modules on Unix

bash-3.00# cd /tmp/Class-Simple-0.19

bash-3.00# perl Makefile.PLChecking if your kit is complete...

Looks good

Writing Makefile for Class::Simple

bash-3.00# /usr/ccs/bin/makecp lib/Class/Simple.pm blib/lib/Class/Simple.pm

Manifying blib/man3/Class::Simple.3

bash-3.00# /usr/ccs/bin/make testPERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0,

'blib/lib', 'blib/arch')" t/*.t

t/anon.............ok

t/attributes.......ok

t/Class-Simple.....ok

t/inherit..........ok

t/isa..............ok

t/nonew............ok

t/override.........ok

All tests successful.

Files=13, Tests=95, 3 wallclock secs ( 0.99 cusr + 0.52 csys = 1.51 CPU)

bash-3.00# /usr/ccs/bin/make installInstalling /usr/perl5/site_perl/5.8.4/Class/Simple.pm

Installing /usr/perl5/5.8.4/man/man3/Class::Simple.3

Writing /usr/perl5/site_perl/5.8.4/i86pc-solaris-64int/auto/Class/Simple/.packli

st

Appending installation info to /usr/perl5/5.8.4/lib/i86pc-solaris-64int/perlloca

l.pod

bash-3.00#

Example:-

18

Danairat T.

Install Perl Module on Windows

1. Unzip the lib file

2. Cd to the downloaded lib

3. ppm install yourdownloadedlib.ppd

19

Danairat T.

Perl Programming Structure

#!/usr/bin/perl

print "Hello, world!\n"; # print to the console

• Declarations and Statements• Semicolons• Whitespace• Comments

20

Danairat T.

Syntax Check and Warning

#!/usr/bin/perl

use strict;

use warnings;

print "Hello, world!\n";

exit (0); # The 0 is to exit the program with success, 1 is to exit with failure

21

The strict checks for unsafe programming constructs. Strict forces a programmer to declare all variables as package or lexically scoped variables. The programmer also needs to use quotes around all strings, and to call each subroutine explicitly.

The warnings print warnings when the Perl compiler detects a possible typographical error and looks for potential problems with mainly look for the most common syntax mistakes and common scripting bugs

Danairat T.

Basic variable - String

• Strings are sequences of characters.

• String literals are usually delimited by either

single (') or double quotes (").

• Double-quoted: To interpret backslash and

variable

• Single-quoted: Not to interpret backslash and

variable except \\ and \'

22

Danairat T.

Basic variable - String

Double-Quoted String Representations

Code Meaning\\\\nnnn Newline

\\\\rrrr Carriage return

\\\\tttt Horizontal tab

\\\\\\\\ Backslash

\\\\"""" Double quote

\b Backspace\u Force next character to uppercase

\l Force next character to lowercase

\U Force all following characters to uppercase

\L Force all following characters to lowercase

\Q Backslash all following non-alphanumeric characters

23

Danairat T.

Basic variable - String

• Examples

#!/usr/bin/perluse strict;use warnings;

print '\tThis is a single quoted string.\n';print "\tThis is a double quoted string.\n";

exit(0);

StringEx01.pl

24

Danairat T.

Basic variable - String

• Examples

#!/usr/bin/perluse strict;use warnings;

print "C:\\WINNT\\Profiles\\\n";print 'C:\WINNT\Profiles\ ', "\n";

exit(0);

StringEx02.pl

25

Danairat T.

Basic variable - String

• Examples

#!/usr/bin/perluse strict;use warnings;

print " \"Hi,\" said Jack. \"Have you read Slashdot today?\" ";

exit(0);

StringEx03.pl

26

Danairat T.

Basic variable - String

• Examples

#!/usr/bin/perluse strict;use warnings;

print ' "Stop," see this. ', "\n";

exit(0);

StringEx04.pl

27

Danairat T.

Quote Constructs

Customary Generic Meaning Interpolates

'''''''' q//q//q//q// Literal string No

"""""""" qqqqqqqq//////// Literal string Yes

() qw// Word list No

// m// Pattern match Yes

s/// s/// Pattern substitution Yes

y/// tr/// Character translation No

28

Danairat T.

Basic variable - String

• The use of q for single quote and qq for double

qoute

• Examples:-

#!/usr/bin/perluse strict;use warnings;print q/"Hi," said Jack. "Have you read Slashdot today?"/ . qq/\n/;print q|"Hi," said Jack. "Have you read Slashdot today?"| . qq|\n|;print q#"Hi," said Jack. "Have you read Slashdot today?"# . qq#\n#;print q("Hi," said Jack. "Have you read Slashdot today?") . qq(\n);print q<"Hi," said Jack. "Have you read Slashdot today?"> . qq<\n>;exit(0);

StringEx05.pl

29

Results:-"Hi," said Jack. "Have you read Slashdot today?""Hi," said Jack. "Have you read Slashdot today?""Hi," said Jack. "Have you read Slashdot today?""Hi," said Jack. "Have you read Slashdot today?""Hi," said Jack. "Have you read Slashdot today?"

Danairat T.

Basic variable - String

• The use of qw for array initialization• Examples:-

#!/usr/bin/perluse strict;use warnings;

my @array1 = ('a', 'lot', 'of', 'quotes', 'is', 'not', 'very', 'legible');print $array1[1] . "\n";

# same result by using the qw and the qw will not interpolate variablesmy @array2 = qw(a lot of quotes is not very legible);print $array2[1] . "\n";

# same result my @array3 = qw(a lotof quotesis notvery legible);print $array3[1] . "\n";exit(0);

StringEx06.pl

30

Results:-

lotlotlot

Danairat T.

Basic variable - String• The use of print <<EOF to write an amount of text within your

program. Perl will interpret as double quote. This can be used

as a format print loop purpose.

• Examples:-

#!/usr/bin/perluse strict;use warnings;

print<<EOT;This is a here-document. It starts on the line after the two arrows,and it ends when the text following the arrows is found at the beginning a line, like thisEOTexit(0);

StringEx07.pl

31

Danairat T.

The $ sign for scalar variable

• Perl use $ represent scalar variable for both

string and number.

32

$theString = “test string”;$theNumber = 25;

#!/usr/bin/perluse strict;use warnings;

my $theString = "test string";print $theString . "\n"; # The . is an concatenate and \n is new line

exit(0);

ScalarVarEx01.pl

Results:-

test string

Danairat T.

Scope of variable my, local

• myThe variable is not visible outside the block in which

it is defined. Recommend to use my variable as it is

faster than local.

• localLocal saves the value of a global variable. Here also

the variable is not accessible outside the block but it

is visible in the subroutine which is called from the

original block. You may need to use local when you

write code in Perl 4

33

Danairat T.

Basic variable - Number

• Perl interpret both float and integer as 32 bits

according to the C compiler that compiled Perl

used.

Integer Literals

1215-200434851_000_000

Float Literals1.25 # about 1 and a quarter7.25e45 # 7.25 times 10 to the 45th power-6.5e24 # negative 6.5 times 10 to the 24th-12e-24 # negative 12 times 10 to the -24th-1.2E-23 # another way to say that

34

Danairat T.

Basic variable - Number

• To represent the non-decimal, we need to provide prefix for

Binary (0b), Octal (0), Hexadecimal (0x)

• Examples:-

#!/usr/bin/perluse strict;use warnings;

print 255, "\n"; # decimal numberprint 0b11111111, "\n"; # 0 or 1print 0377, "\n"; # 0 to 7print 0xFF, "\n"; # 0 to F

exit(0);

NumberEx01.pl

35

Results:-

255255255255

Danairat T.

Number ConversionConvert BIN to DEC

• $number = 0b10110110;

Convert OCT to DEC

• $dec = 033653337357;

• $dec = oct("33653337357");

Convert HEX to DEC

• $dec = 0xDEADBEEF;

• $dec = hex("DEADBEEF");

Convert DEC to BIN

• $bin = sprintf("%b", 3735928559);

Convert DEC to OCT

• $oct = sprintf("%o", 3735928559);

Convert DEC to HEX

• $hex = sprintf("%X", 3735928559); # upper case A-F

• $hex = sprintf("%x", 3735928559); # lower case a-f

36

Danairat T.

Operators Precedence

Associativity OperatorLeft The "list" operators (leftward) eg. print(), sort(),

Left -> (method call, dereference)

Nonassociative ++++++++ -------- (autoincrement, autodecrement)

Right ******** (exponentiation)

Left =~=~=~=~ !~!~!~!~ (matches, doesn't match)

Left **** //// %%%% xxxx (multiply, divide, modulus, string replicate)

Left ++++ ---- .... (add, subtract, string concatenate)

Left << >>

Nonassociative Named unary operators (like chomp)

Nonassociative < > <= >= lt gt le ge

Nonassociative == != <=> eq ne cmp

Left & (bit-and)

Left | ^ (bit-or, bit-xor)

Nonassociative .. ... (noninclusive and inclusive range)

Right ?: (if-then-else)

Right = += -= *=, etc. (assignment and binary-assignment)

Left , => (comma and comma-arrow)

Nonassociative List operators (rightward)

Right not (logical not)

Left and (logical and)

Left or xor (logical or, logical xor)

37

Danairat T.

Operators• Examples:-

#!/usr/bin/perluse strict;use warnings;

print 2 + 118 . "\n";print 3 + 2 * 15 . "\n";print(3 + 2) * 15; # list operator impact to print()print "\n";print((3 + 2) * 15);print "\n";print 2**4 . ", " . -2**4 . "\n";print (2**4 . ", " . (-2)**4 . "\n");

exit(0);

Results:-

1203357516, -1616,16

OperatorEx01.pl

38

Danairat T.

Repetition Operators

• The string repetition operator (x) does to a left operand string.

The number 5 is converted to the string "5". This new string is

then copied four times as 5555

• Examples:-

#!/usr/bin/perluse strict;use warnings;

print ((3+2) x 4);

exit(0);

RepetitionEx01.pl

39

Results:-

5555

Danairat T.

Comparison Operators

• Perl always requires you to specify the proper type of

comparison, whether it be numeric or string.Remarks: 7 is less than 30, but the string "30" comes before the string "7" (because the

ASCII value for 3 is less than the value for 7)

Comparison Numeric String

Equal == eq

Not equal != ne

Less than < lt

Greater than > gt

Less than or equal to <= le

Greater than or equal to >= ge

40

Danairat T.

Comparison Operators

• Examples:-

#!/usr/bin/perluse strict;use warnings;

print 15==15; # trueprint "\n";print 15==20; # falseprint "\n";print 100 < 5; # falseprint "\n";print 100 lt 5; # trueexit (0);

CompareEx01.pl

41

Results:-

1

1

Danairat T.

String Operator

• Built-in Auto Converting Strings into Numbers

• Examples:-

#!/usr/bin/perluse strict; use warnings;

# define a numeric stringmy $scalar = '123.4e5';

# evaluate it in original string contextprint $scalar; # produces '123.4e5'print "\n";

# evaluate it in numeric contextprint $scalar + 1; # produces '12340001'print "\n";

exit(0);

AutoConvertEx01.pl

42

Results:-

123.4e512340001

Danairat T.

String Operator

• Converting Strings into Array using Split unary operator

• Examples:-

#!/usr/bin/perluse strict; use warnings;

$csv = "one , two , three , four , five , six";@list1 = split(', ' , $csv); # function styleprint @list1;print "\n";@list2 = split /, /, $csv; # regular expression styleprint @list2;print "\n";@list3 = split /\s*, \s*/, $csv; # regular expression style with trim the delimiterprint @list3;print "\n";

exit(0);

Results:-

one two three four five sixone two three four five sixonetwothreefourfivesix

SplitStringEx01.pl

43

Danairat T.

Perl Array

• A dynamic storage for a list which can be

grown, shrunk, alter. The array variable starts

prefix with an at-sign @

44

@numberArray = (1, 2, 3, 4, 5, 6);@stringArray = ('one', 'two', 'three', 'four', 'five');@myArray = ('one', 'two', 'three', 4, 'five');@stringArray = qw(one two three four five);@stringArray = qw(onetwothreefourfive);

Danairat T.

Perl Array - Examples• Assign values to array and loop display value from array

45

#!/usr/bin/perluse strict;use warnings;

my @array = (); # initialize an array$array[0] = "1st ";$array[4] = "5th ";@array[1..3, 5, -1] = ("2nd ", "3rd ", "4th ", "6th ", "Last");

foreach my $theRest (@array ) {print $theRest;

}

exit(0);

ManipulateArrayEx01.pl

Results:-

1st 2nd 3rd 4th 5th Last

Danairat T.

Perl Array - Examples• Using scalar to get arrays size and last position of an array $#

46

#!/usr/bin/perluse strict;use warnings;

my @myArray = ('one', 'two', 'three', 4, 'five');my $arraySize = scalar(@myArray);

print "The Array size is: " . $arraySize . "\n";print "The last element is: " . $myArray[$#myArray] . "\n";

exit(0);

ArraySizeEx01.pl

Results:-

The Array size is: 5

The last element is: five

Danairat T.

Perl Array - Examples• Adding element to array using push

47

#!/usr/bin/perluse strict;use warnings;

my @myArray = ('one', 'two', 'three', 4, 'five');$myArray[scalar(@myArray)] = ‘six’; # adding the new element;push (@myArray, ’seven’);

print "The Array size is: " . scalar(@myArray) . "\n";print "The last element is: " . $myArray[$#myArray] . "\n";

exit(0);

AddingArrayEx01.pl

Results:-

The Array size is: 7

The last element is: seven

Danairat T.

Perl Array - Examples• Removing last elements from an Array using pop

48

#!/usr/bin/perluse strict;use warnings;

my @array = (1, 2, 3, 4, 5, 6);push (@array, '7'); print "@array\n"; my $last = pop @array; print "$last\n"; # print 7print "@array\n";

exit(0);

PopArrayEx01.pl

Results:-

1 2 3 4 5 6 7

7

1 2 3 4 5 6

Danairat T.

Perl Array - Examples• Adding element to array at position zero using unshift• The below is equivalent to: splice @array, 0, 0, @more;

49

#!/usr/bin/perluse strict;use warnings;

my @myArray = ('one', 'two', 'three', 4, 'five');unshift (@myArray, 'first_added', 'second_added'); # adding element at first

print "The Array size is: " . scalar(@myArray) . "\n";print "The last element is: " . $myArray[$#myArray] . "\n";print "The array element values are: @myArray \n";

exit(0);

UnshiftArrayEx01.pl

Results:-

The Array size is: 7

The last element is: five

The array element values are: first_added second_added one two three 4 five

Danairat T.

Perl Array - Examples• Removing first elements from an Array using shift

50

#!/usr/bin/perluse strict;use warnings;

my @array = (1, 2, 3, 4, 5, 6);print "The starting array is @array\n"; # array is now (1, 2, 3, 4, 5, 6, 7)

unshift (@array, -1, 0);print "Array after unshift is @array\n"; # array is now (-1, 0, 1, 2, 3, 4, 5, 6)

my $shiftValue = shift @array; # remove the first element of the arrayprint "shiftValue is: " . $shiftValue . "\n";$shiftValue = shift @array; # remove the first element of the arrayprint "shiftValue is: " . $shiftValue . "\n";print "The rest elements are: @array\n";

exit(0);

ShiftArrayEx01.pl

Results:-

The starting array is 1 2 3 4 5 6

Array after unshift is -1 0 1 2 3 4 5 6

shiftValue is: -1

shiftValue is: 0

The rest elements are: 1 2 3 4 5 6

Danairat T.

Perl Array - Examples• Flexible copy an array

51

#!/usr/bin/perluse strict;use warnings;

my @myArray = ('one', 'two', 'three', 4, 'five');my $firstPosition; my @myArray2 = (); my @myArray3 = ();

($firstPosition, @myArray2[0..1], @myArray3) = @myArray;

print $firstPosition . "\n"; # print the first element

foreach my $theRest (@myArray2) {print $theRest . "\n"; # print element from myArray2

}

exit(0);

CopyArrayEx01.pl

Results:-

one

two

three

Danairat T.

Perl Array - Examples• Resizing and Truncating an Array. The below is fastest way to

resize an array.

52

#!/usr/bin/perluse strict;use warnings;

my @myArray = ("apple ", "banana ", "orange ");print "Array size is: ". scalar(@myArray) . "\n";$#myArray = 99; # increase an array size to 100 without assign valueprint "Array size is: ". scalar(@myArray) . "\n";$#myArray = 1; # decrease an array size to 2print "Array size is: ". scalar(@myArray) . "\n";print "Array element values are: @myArray \n";

exit(0);

ResizeArrayEx01.pl

Results:-

Array size is: 3

Array size is: 100

Array size is: 2

Array element values are: apple banana

Danairat T.

Perl Array - Examples• Remove all elements

53

#!/usr/bin/perluse strict;use warnings;

my @myArray = ("apple ", "banana ", "orange ");print "Array size is: ". scalar(@myArray) . "\n";@myArray = (); # remove all elements and return memory to OSprint "Array size is: ". scalar(@myArray) . "\n";

exit(0);

RemoveAllElementsArrayEx02.pl

Results:-

Array size is: 3

Array size is: 0

Danairat T.

Perl Array - Examples• Sorting Arrays using sort

54

#!/usr/bin/perluse strict;use warnings;

my @words = ('here', 'are', 'some', 'words');my @alphabetical = sort @words;print "The starting array: @words \n";print "The sorted array: @alphabetical \n";

exit(0);

SortArrayEx02.pl

Results:-The starting array: here are some words

The sorted array: are here some words

Danairat T.

Perl Array - Examples• Reversing Arrays using reverse. This is only to reverse an array

but not to do reverse-sort array.

55

#!/usr/bin/perluse strict;use warnings;

my @words = ('here', 'are', 'some', 'words');my @alphabetical = reverse @words;print "The starting array: @words \n";print "The reversed array: @alphabetical \n";

exit(0);

ReverseArrayEx02.pl

Results:-The starting array: here are some words

The sorted array: words some are here

Danairat T.

Perl Array - Examples• Reversing Sort Arrays using sort

56

#!/usr/bin/perluse strict;use warnings;

my @words = ('here', 'are', 'some', 'words');my @alphabetical = sort {$b cmp $a} @words;print "The starting array: @words \n";print "The reversed sort array: @alphabetical \n";

exit(0);

ReverseArrayEx02.pl

Results:-The starting array: here are some words

The reversed sorted array: words some here are

Danairat T.

Perl Array - Examples• Numbering sort using {$a <=> $b}. The built-in global variables

$a and $b for sorting algorithms

57

#!/usr/bin/perluse strict;use warnings;

my @words = ('100', '5', '2000', '9');my @sortArray = sort {$a <=> $b} @words;print "The starting array: @words \n";print "The sorted array: @sortArray \n";

exit(0);

NumberSortedArrayEx02.pl

Results:-The starting array: 100 5 2000 9

The sorted array: 5 9 100 2000

Danairat T.

Perl Array - Examples• Alphanumeric (mixed) sort using {int($a) <=> int($b) or $a cmp $b}. The

<=> is for number and cmp is for character comparison.

58

#!/usr/bin/perluse strict;use warnings;

my @words = ("1000", "zebra", "100", "apple", "5", "2000", "9");my @sortArray = sort {int($a) <=> int($b) or $a cmp $b} @words;print "The starting array: @words \n";print "The sort array: @sortArray \n";

exit(0);

AlphaSortedArrayEx02.pl

Results:-Argument "zebra" isn't numeric in int at test.pl line 6.

Argument "apple" isn't numeric in int at test.pl line 6.

The starting array: 1000 zebra 100 apple 5 2000 9

The sort array: apple zebra 5 9 100 1000 2000

Danairat T.

Perl Array - Examples• Converting array into scalar using join

59

#!/usr/bin/perluse strict;use warnings;

my @words = ("1000", "zebra", "100", "apple", "5", "2000", "9");print "The starting array: @words \n";@words = sort {int($a) <=> int($b) or $a cmp $b} @words;print "The sorted array: @words \n";

my $scalarWords = join ("\|", @words);print "The result is: $scalarWords \n";

exit(0);

SalarFromArrayEx02.pl

Results:-

The starting array: 1000 zebra 100 apple 5 2000 9

Argument "zebra" isn't numeric in int at test.pl line 7.

Argument "apple" isn't numeric in int at test.pl line 7.

The sorted array: apple zebra 5 9 100 1000 2000

The result is: apple|zebra|5|9|100|1000|2000

Danairat T.

Perl Array - Examples• Converting scalar to array using split

60

#!/usr/bin/perluse strict;use warnings;

my $words = "apple|zebra|5|9|100|1000|2000";my @wordsArray = split (/\|/, $words);print "The result is: @wordsArray \n";

exit(0);

ArrayFromSplitEx02.pl

Results:-

The result is: apple zebra 5 9 100 1000 2000

Danairat T.

Perl Array - Examples• Replace and insert elements in array using splice

splice @array, $from, $quantity, @replacement;

61

#!/usr/bin/perluse strict;use warnings;

my @array = ('a', 'b', 'c', 'd', 'e', 'f');

# replace third element with three new elementsmy $removed = splice @array, 2, 1, (1, 2, 3);print "The array values are: @array \n";print "The removed element is: $removed \n";

exit(0);

ReplaceInsertArrayEx01.pl

Results:-

The array values are: a b 1 2 3 d e f

The removed element is: c

Danairat T.

Perl Array - Examples• Remove elements in array using splice

splice @array, $from, $quantity;

62

#!/usr/bin/perluse strict;use warnings;

my @array = ('a', 'b', 'c', 'd', 'e', 'f');# remove elements 2, 3 and 4my @removed = splice @array, 2, 3; # start from position#2 for 3 positionsprint "The rest elements are: @array\n"; print "The removed elements are: @removed\n";

exit(0);

RemoveElementsArrayEx01.pl

Results:-

The rest elements are: a b f

The removed elements are: c d e

Danairat T.

Perl Array - Examples• Remove elements to the end of the array using splice

splice @array, $quantity;

63

#!/usr/bin/perluse strict;use warnings;

my @array = ('a', 'b', 'c', 'd', 'e', 'f');# remove last three elementsmy @last_4_elements = splice @array, -4; # start from last pos of 4 to the endprint "@array\n"; print "@last_4_elements\n";

exit(0);

RemoveElementsArrayEx02.pl

Results:-

a b

c d e f

Danairat T.

Date and Time

• The epochThe epoch system, as used most operating systems, represents a datetime

as the number of seconds after a specific date and time. For Unix systems,

the epoch began on January 1, 1970 at midnight GMT (UTC).

time()

• Local time

The local time is UTC plus the local time zone offset. While UTC is great for

internal use, most people want to see datetimes in terms of their location.

localtime()

64

Danairat T.

Date and Time

• Example:-

65

#!/usr/bin/perluse strict;use warnings;

my $myEpoch = time(); # time in second that counting from 1 Jan 1970print $myEpoch . "\n";

my $myDatetime = localtime($myEpoch); # auto convert to scalarprint $myDatetime . "\n";

exit(0);

DateAndTimeEx01.pl

Results:-

1258345951

Mon Nov 16 11:32:31 2009

Danairat T.

Date and Time

• The Local Time

The Local Time can be return value in scalar or in array and

provide you to get the value in day, month, year, hh, mm, etc.

66

$sec - seconds [0-60, to allow for leap seconds] $min - minutes [0-59], $hour - hours [0-23], $mday - day of the month [1-31] (Note: from '1'), $mon - month [0-11] (Jan. is '0'), $year - number of years since 1900 (1999 is 99; 2000 is 100), $wday - day of the week [0-6] (Sun. is '0'), $yday - day of the year [0-365] (total of 366 possible for leap year) $isdst - daylight savings time [0,1] -- returns boolean '0' or '1' if Daylight Savings active.

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time());

Danairat T.

Date and Time

• Example:-

67

#!/usr/bin/perluse strict;use warnings;

my $myEpoch = time(); # time counting from 1 Jan 1970print $myEpoch . "\n";

my $myDatetime = localtime($myEpoch); # auto convert to scalarprint $myDatetime . "\n";

my @myTimeData = localtime($myEpoch); # same as localtime() but use the fixed value from previous varprint join (" ", @myTimeData) . "\n";

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = @myTimeData;printf "%4d-%02d-%02d %02d:%02d:%02d\n", $year+1900,$mon+1,$mday,$hour,$min,$sec;

exit(0);

LocalTimeEx01.pl

Results:-1258346693

Mon Nov 16 11:44:53 2009

53 44 11 16 10 109 1 319 0

2009-11-16 11:44:53

Danairat T.

Date and Time

• Date/Time calculation can be done by using the epoch time

68

use Time::Local;

my $time = timelocal($sec,$min,$hours,$day,$month,$year); # replace 'timelocal' with 'timegm' if your input date is GMT/UTC

Danairat T.

Date and Time

• Date/Time calculation can be done by using the epoch time

69

#!/usr/bin/perluse strict;use warnings;use Time::Local;

my $myCurrentTimeEpoch = time(); # time counting from 1 Jan 1970my $myCurrentDatetime = localtime($myCurrentTimeEpoch); # auto convert to scalarprint "myCurrentTimeEpoch is: " . $myCurrentTimeEpoch . "\n";print "myCurrentDatetime is: " . $myCurrentDatetime . "\n";

my $myTimeEpoch = timelocal(0,0,0,14,10,109); # 14-Nov-2009 14:30print "myTimeEpoch is: " . $myTimeEpoch . "\n";

my $myDiffTime = $myCurrentTimeEpoch - $myTimeEpoch;print '$myCurrentTimeEpoch - $myTimeEpoch =' . $myDiffTime . "\n";

my $myDiffDay = int($myDiffTime / (3600 * 24));print "myDiffDay is: " . $myDiffDay . "\n";

exit(0);

DateTimeCalcEx01.pl

Results:-myCurrentTimeEpoch is: 1258356343

myCurrentDatetime is: Mon Nov 16 14:25:43 2009

myTimeEpoch is: 1258131600

$myCurrentTimeEpoch - $myTimeEpoch =224743

myDiffDay is: 2

Danairat T.

Perl Hash

• A compound data type as in key value pairs.

• Hash has no ‘first’ or ‘last’ element like in an array.

• Hashes consist of paired values, Perl provides the =>

operator as an alternative to the comma.

my %myHash = (Mouse => 'Jerry', Cat => 'Tom', Dog => 'Spike');

– Hash variable use % as a represent sign.

– Hash values can be any scalar.

– Hash keys can only be strings. The => operator also allows us to omit the

quotes by treating its left-hand side as a constant string.

70

Danairat T.

Perl Hash- Examples

• Add, modify and display Hash table

• Basic Hash Examples:-

71

#!/usr/bin/perluse strict;use warnings;

my %myHash = (Mouse => 'Jerry', Cat => 'Tom');$myHash{'Dog'} = 'Spike';@myHash{'Bird', 'Fish'} = ('Tweet', 'Nemo'); # it is @hash{@keys} = @values;

$myHash{'Dog'} = 'Bark';

foreach my $myKey (sort keys %myHash) {print "$myKey => $myHash{$myKey} \n";}

exit(0);

HashEx01.pl

Results:-

Bird => Tweet

Cat => Tom

Dog => Bark

Fish => Nemo

Mouse => Jerry

Danairat T.

Perl Hash- Examples

• Hash keys and values

72

#!/usr/bin/perluse strict;use warnings;

# define a default set of hash keys and valuesmy %myHash = (Cat => 'Tom', Mouse => 'Jerry');

my @myKeys = keys %myHash;my @myValues = values %myHash;

print “Keys are: @myKeys”;print “Values are: @myValues”;

exit(0);

HashKeysValuesEx01.pl

Results:-

Keys are: Mouse Cat

Values are: Jerry Tom

Danairat T.

Perl Hash- Examples

• Removing Hash Keys and Values

73

#!/usr/bin/perluse strict;use warnings;

my %myHash = ();%myHash = (Mouse => 'Jerry', Cat => 'Tom');print "01 Starting result: " . $myHash{'Cat'} . "\n";

undef $myHash{'Cat'};if (defined $myHash{'Cat'}) {print "02 Key is still defined: " . $myHash{'Cat'} . "\n"; # error complain here

}if (exists $myHash{'Cat'}) {print "03 Key is still exist: " . $myHash{'Cat'} . "\n"; # no error but no value

}

delete $myHash{'Cat'};if (exists $myHash{'Cat'}) {print "04 Delete result:" . $myHash{'Cat'} . "\n";

} exit(0);

HashRemoveValueEx01.pl

Results:-

01 Starting result: Tom

Use of uninitialized value in concatenation

(.) or string at test.pl line 14.

03 Key is still exist:

Danairat T.

Perl Hash- Examples

• Combine hashes

• Basic Hash Examples:-

74

#!/usr/bin/perluse strict;use warnings;

# define a default set of hash keys and valuesmy %default_animals = (Cat => 'Tom', Mouse => 'Jerry');

# get another set of keys and valuesmy %input_animals = (Cat => 'Ginger', Mouse => 'Jerry');

# combining keys and values with overridesmy %animals = (%default_animals, %input_animals);print "$animals{Cat}\n"; # prints 'Ginger'

exit(0);

HashCombineEx01.pl

Results:-

Ginger

Danairat T.

Perl Hash- Examples

• Converting Hash into Array using simply =

75

#!/usr/bin/perluse strict;use warnings;

# define a default set of hash keys and valuesmy %myHash = (Cat => 'Tom', Mouse => 'Jerry');

foreach my $myKey (keys %myHash) {print "$myKey with value $myHash{$myKey} \n";

}

my @myArray = %myHash;foreach my $myElement (@myArray) {

print "myElement is $myElement \n";}exit(0);

ArrayFromHashEx01.pl

Results:-

Mouse with value Jerry

Cat with value Tom

myElement is Mouse

myElement is Jerry

myElement is Cat

myElement is Tom

Danairat T.

Perl Hash- Examples

• Converting hash into array when the hash contain undef value

76

#!/usr/bin/perluse strict;use warnings;

# define a default set of hash keys and valuesmy %myHash = (Cat => 'Tom', Mouse => 'Jerry');

foreach my $myKey (keys %myHash) {print "$myKey with value $myHash{$myKey} \n";

}undef $myHash{'Mouse'};

my @myArray = %myHash;foreach my $myElement (@myArray) {

print "myElement is $myElement \n";}exit(0);

ArrayFromHashEx02.pl

Results:-

Mouse with value Jerry

Cat with value Tom

myElement is Mouse

Use of uninitialized value in concatenation

(.) or string at example.pl line 15.

myElement is

myElement is Cat

myElement is Tom

Danairat T.

Perl Hash- Examples

• Named Arguments for Hash passing to Subroutines

• Perl have no built-in %_ variable. You need to use @_

77

#!/usr/bin/perluse strict;use warnings;

# define a default set of hash keys and valuesmy %myHash = (Cat => 'Tom', Mouse => 'Jerry');

sub hashProcess {my %mySubHash = @_;foreach my $myKey (keys % mySubHash) {

print "$myKey with value $ mySubHash{$myKey} \n";}

}exit(0);

HashPassingEx01.pl

Results:-

Mouse with value Jerry

Cat with value Tom

Danairat T.

Flow Control and Loop

• Block

• If, elsif, else

• Unless

• While

• For

• For each

• Do.. until

78

Danairat T.

Flow Control and Loop

• Program Blocks is construct that allows several statements

within in curly braces. The block also defines a new scope in

which variables can be declared and used

{

STATEMENT;

STATEMENT;

... ;

STATEMENT;

}

79

Danairat T.

Flow Control and Loop

• A bare block Example:-

80

use strict;use warnings;

my $myString = "Hi";{

my $myString = "Hello";print "myString inside the block is $myString \n";

}

print "myString outside the block is $myString \n";

exit(0);

BlockEx01.pl

Results:-

myString inside the block is Hello

myString outside the block is Hi

Danairat T.

Flow Control and Loop

• The Special block: BEGIN, INIT, END. Perl will perform BEGIN then INIT then

END block.

81

#!/usr/bin/perluse strict;use warnings;

END {print "Ending... \n";

}

print "No Block Code Here... \n";

INIT {print "Initializing...\n";

}

BEGIN {print "Beginning.. \n";

}

exit(0);

SpecialBlockEx01.pl

Results:-

Beginning..

Initializing...

No Block Code Here...

Ending...

Danairat T.

Flow Control and Loop

• 'if‘ : The condition logic, basic form:-

if (EXPRESSION) BLOCK

• Invert the syntax of an if statement put the BLOCK first.

BLOCK if EXPRESSION;

STATEMENT if EXPRESSION;

• In this case we can both omit the parentheses of the condition and also

replace the block with a bare statement

82

Danairat T.

Flow Control and LoopIf, then, and else conditions are implemented with the else keyword:

if (EXPRESSION) BLOCK else BLOCK

83

if ($greet1 eq “Hello”) {if ($greet2 eq “HI”) {

print "true \n";} else {

print "false \n";}

} else {print “No Greeting\n";

}

1st if

1st else

2nd if

2nd else

Danairat T.

Flow Control and Loop

• elsif for multiple conditions chains.

if (EXPRESSION) BLOCK elsif (EXPRESSION) BLOCK elsif...

if (EXPRESSION) BLOCK elsif (EXPRESSION) BLOCK else BLOCK

84

The equivalent code using elsif is simpler:

if ($a eq $b) {print "Equal";

} elsif ($a gt $b) {print "Greater";

} else {print "Less";

}

For example, to compare strings using just if and else we might write:

if ($a eq $b) {print "Equal";

} else {if ($a gt $b) {

print "Greater";} else {

print "Less";}

}

Danairat T.

Flow Control and Loop

• unless (“if not”): The unless is very useful to check the

conditions and return (or exit program) if the conditions did

not match with expectation.

Below is the same result but “unless” make the code simpler.

85

if (not open FILE, $filename) {return "Failed to open $filename";}

return "Failed to open $filename" unless (open FILE, $filename);

Danairat T.

Flow Control and Loop

• The Ternary Operator works as an expression and returns a value that

can be assigned in other expressions.

expression1 ? expression2 : expression3

86

#!/usr/bin/perluse strict;use warnings;

my $check = “exist”;

my $customerStatus = (if $check eq "exist") ? "Existing" : "New";

print “$customerStatus \n";

exit(0);

TernaryEx01.pl

Results:-

Existing

Danairat T.

Flow Control and LoopSwitches: the block contains a multiple-branch condition.

SWITCH: label prefixes the block to indicate that

87

#!/usr/bin/perluse strict;use warnings;

print<<EOT;select on of:-1. Menu12. Menu23. Menu3EOT

print "Please enter choice 1, 2 or 3 :"; my $input = <STDIN>;chomp($input);switch: {

$input eq '1' and do { printLabel($input); last; }; $input eq '2' and do { printLabel($input); last; };$input eq '3' and do { printLabel($input); last; };

}sub printLabel {

my ($label, @others) = @_;print "label is: " . $label . "\n";

}exit(0);

SwitchEx01.pl

Results:-

select on of:-

1. Menu1

2. Menu2

3. Menu3

Please enter choice 1, 2 or 3 :3

label is: 3

Danairat T.

Flow Control and Loop

LoopsThe block of code that is executed repeatedly, according to

the criteria of the loop's controlling conditions.

Both kinds of loop can be controlled using statements using next, last.

88

- Iterating loops, provided by for and foreach- Conditional loops, provided by while and until.

Danairat T.

Flow Control and Loop

For loop and Foreach loop

89

foreach (@array) {print "$_ \n";

}

foreach my $element (@array) {print $element,"\n";

}

for ($n = 0; $n < $#array; $n ++) {print $array [$n], "\n";

}

or

Danairat T.

Flow Control and Loop

while, until, and do loopThe conditional Loops to execute the loop for so long as the

condition holds.

90

#!/usr/bin/perluse warnings;use strict;

my $n = 0;while ($n++ < 10) {print $n . "\n";}

WhileEx01.pl

Results:-

1

2

3

4

5

6

7

8

9

10

Danairat T.

Flow Control and Loop

do...while and do...untilThe loop can ensure that the body is executed at least once.

91

#!/usr/bin/perluse warnings;use strict;

my $input;do {

$input = <STDIN>;print "You typed: $input \n";

} while ($input !~ /^quit/);

exit(0);

#!/usr/bin/perluse warnings;use strict;

my $input;do {

$input = <STDIN>;print "You typed: $input \n";

} until ($input =~ /^quit/);

exit(0);

Danairat T.

Flow Control and Loop

Controlling Loop Executionnext, which go to the next iteration (testing the loop condition),

last, which immediately exits the loop

redo, which restarts the current iteration (without retesting the loop condition).

92

#!/usr/bin/perluse warnings;use strict;

# define a selection of strings one of which is 'start'my @lines = ("this", "that", "the other", "start", "the data", "we want");

# discard lines until we see the 'start' markerwhile (my $line = shift @lines) {last if $line eq 'start';}

# print out the remaining elements using interpolation ($")print "@lines";exit (0);

WhileWithShiftEx01.pl

Results:-

the data we want

Danairat T.

Flow Control and Loop

map

map EXPRESSION, LIST

map BLOCK LIST

• Map is to convert the elements of a list one by one, and produce a new list

as a result.

• The expression or block performs the conversion, so map is conceptually

related to a foreach loop. functions perform aliasing $_

93

Danairat T.

Flow Control and Loop

map

94

#!/usr/bin/perluse warnings;use strict;

my @myNames = ('jacob', 'alexander', 'ethan', 'andrew');my @ucNames = map(ucfirst($_), @myNames);

print "@ucNames" . "\n";

exit(0);

MapEx01.pl

Results:-

Jacob Alexander Ethan Andrew

Danairat T.

Flow Control and Loop

grep

grep EXPRESSION, LIST

grep BLOCK LIST

• grep is to return a list containing a subset of the original list.

• The expression or block is evaluated to a True or False value to see if the

element is eligible for inclusion, so grep is conceptually related to a while

loop. functions perform aliasing $_

95

Danairat T.

Flow Control and Loop

grep

96

#!/usr/bin/perluse warnings;use strict;

my @myNames = ('Jacob', 'Michael', 'Joshua', 'Matthew', 'Alexander', 'Andrew');my @grepNames = grep(/^A/, @myNames);

print "@grepNames" . "\n";

exit(0);

GrepEx01.pl

Results:-

Alexander Andrew

Danairat T.

Line ID: Danairat

FB: Danairat Thanabodithammachari

+668-1559-1446

Thank you

Recommended