Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of...

68
Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings. @colors = qw (red blue green black); @sort_colors = sort @colors # Array @sort_colors is (black blue green red)

Transcript of Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of...

Page 1: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Sort the Elements of an ArrayUsing the lsquosortrsquo keyword by default

we can sort the elements of an array lexicographically

Elements considered as strings colors = qw (red blue green black)sort_colors = sort colors Array sort_colors is (black blue

green red)

Another example

num = qw (10 2 5 22 7 15) new = sort num new will contain (10 15 2 22 5 7)

How do sort numerically

num = qw (10 2 5 22 7 15)new = sort $a lt=gt $b num new will contain (2 5 7 10 15 22)

The lsquosplicersquo function

Arguments to the lsquosplicersquo functionThe first argument is an arrayThe second argument is an offset (index

number of the list element to begin splicing at)

Third argument is the number of elements to remove

colors = (ldquoredrdquo ldquogreenrdquo ldquobluerdquo ldquoblackrdquo)

middle = splice (colors 1 2) middle contains the elements removed

File Handling

Interacting with the user

Read from the keyboard (standard input)Use the file handle ltSTDINgtVery simple to useprint ldquoEnter your name rdquo$name = ltSTDINgt Read from

keyboardprint ldquoGood morning $name nrdquo$name also contains the newline

character Need to chop it off

The lsquochoprsquo FunctionThe lsquochoprsquo function removes the last

character of whatever it is given to chopIn the following example it chops the

newlineprint ldquoEnter your name rdquo chop ($name = ltSTDINgt) Read from keyboard and chop newlineprint ldquoGood morning $name nrdquolsquochoprsquo removes the last character

irrespective of whether it is a newline or not Sometimes dangerous

Safe chopping lsquochomp

The lsquochomprsquo function works similar to lsquochoprsquo with the difference that it chops off the last character only if it is a newline

print ldquoEnter your name rdquochomp ($name = ltSTDINgt) Read from keyboard and chomp newlineprint ldquoGood morning $name nrdquo

File Operations

Opening a file The lsquoopenrsquo command opens a file and

returns a file handleFor standard input we have a

predefined handle ltSTDINgt$fname = ldquohomeisgreporttxtrdquo

while (ltXYZgt) print ldquoLine number $ $_rdquo

open XYZ $fname

Checking the error code$fname = ldquohomeisgreporttxtrdquoopen XYZ $fname or die ldquoError in open $rdquowhile (ltXYZgt) print ldquoLine number $ $_rdquo$ returns the line number (starting at 1)$_ returns the contents of last match$ returns the error codemessage

Reading from a file

The last example also illustrates file reading

The angle brackets (lt gt) are the line input operators

The data read goes into $_

Writing into a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogt$outrdquo or die ldquoError in write

$rdquofor $i (120) print XYZ ldquo$i Hello the time isrdquo

scalar(localtime) ldquonrdquo

Appending to a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogtgt$outrdquo or die ldquoError in

write $rdquofor $i (120) print XYZ ldquo$i Hello the time

isrdquoscalar(localtime) ldquonrdquo

Closing a file

where XYZ is the file handle of the file being closed

close XYZ

Printing a file

This is very easy to do in Perl $input = ldquohomeisgreporttxtrdquo open IN $input or die ldquoError in

open $rdquowhile (ltINgt) printclose IN

Command Line Arguments

Perl uses a special array called ARGVList of arguments passed along with the

script name on the command lineExample if you invoke Perl as perl testpl red blue green then ARGV

will be (red blue green)Printing the command line argumentsforeach (ARGV) print ldquo$_ nrdquo

Standard File HandlesltSTDINgtRead from standard input (keyboard)ltSTDOUTgtPrint to standard output (screen)ltSTDERRgtFor outputting error messagesltARGVgtReads the names of the files from the

command line and opens them all

ARGV array contains the text after the programrsquos name in command line

ltARGVgt takes each file in turnIf there is nothing specified on the

command line it reads from the standard input

Since this is very commonly used Perl provides an abbreviation for ltARGVgtnamely lt gt

An example is shown

$lineno = 1while (lt gt) print $lineno ++print ldquo$lineno $_rdquoIn this program the name of the file has

to be given on the command lineperl list_linespl file1txtperl list_linespl atxt btxt ctxt

Control Structures

IntroductionThere are many control constructs in

PerlSimilar to those in CWould be illustrated through

examplesThe available constructs forforeachifelseifelsewhiledo etc

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 2: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Another example

num = qw (10 2 5 22 7 15) new = sort num new will contain (10 15 2 22 5 7)

How do sort numerically

num = qw (10 2 5 22 7 15)new = sort $a lt=gt $b num new will contain (2 5 7 10 15 22)

The lsquosplicersquo function

Arguments to the lsquosplicersquo functionThe first argument is an arrayThe second argument is an offset (index

number of the list element to begin splicing at)

Third argument is the number of elements to remove

colors = (ldquoredrdquo ldquogreenrdquo ldquobluerdquo ldquoblackrdquo)

middle = splice (colors 1 2) middle contains the elements removed

File Handling

Interacting with the user

Read from the keyboard (standard input)Use the file handle ltSTDINgtVery simple to useprint ldquoEnter your name rdquo$name = ltSTDINgt Read from

keyboardprint ldquoGood morning $name nrdquo$name also contains the newline

character Need to chop it off

The lsquochoprsquo FunctionThe lsquochoprsquo function removes the last

character of whatever it is given to chopIn the following example it chops the

newlineprint ldquoEnter your name rdquo chop ($name = ltSTDINgt) Read from keyboard and chop newlineprint ldquoGood morning $name nrdquolsquochoprsquo removes the last character

irrespective of whether it is a newline or not Sometimes dangerous

Safe chopping lsquochomp

The lsquochomprsquo function works similar to lsquochoprsquo with the difference that it chops off the last character only if it is a newline

print ldquoEnter your name rdquochomp ($name = ltSTDINgt) Read from keyboard and chomp newlineprint ldquoGood morning $name nrdquo

File Operations

Opening a file The lsquoopenrsquo command opens a file and

returns a file handleFor standard input we have a

predefined handle ltSTDINgt$fname = ldquohomeisgreporttxtrdquo

while (ltXYZgt) print ldquoLine number $ $_rdquo

open XYZ $fname

Checking the error code$fname = ldquohomeisgreporttxtrdquoopen XYZ $fname or die ldquoError in open $rdquowhile (ltXYZgt) print ldquoLine number $ $_rdquo$ returns the line number (starting at 1)$_ returns the contents of last match$ returns the error codemessage

Reading from a file

The last example also illustrates file reading

The angle brackets (lt gt) are the line input operators

The data read goes into $_

Writing into a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogt$outrdquo or die ldquoError in write

$rdquofor $i (120) print XYZ ldquo$i Hello the time isrdquo

scalar(localtime) ldquonrdquo

Appending to a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogtgt$outrdquo or die ldquoError in

write $rdquofor $i (120) print XYZ ldquo$i Hello the time

isrdquoscalar(localtime) ldquonrdquo

Closing a file

where XYZ is the file handle of the file being closed

close XYZ

Printing a file

This is very easy to do in Perl $input = ldquohomeisgreporttxtrdquo open IN $input or die ldquoError in

open $rdquowhile (ltINgt) printclose IN

Command Line Arguments

Perl uses a special array called ARGVList of arguments passed along with the

script name on the command lineExample if you invoke Perl as perl testpl red blue green then ARGV

will be (red blue green)Printing the command line argumentsforeach (ARGV) print ldquo$_ nrdquo

Standard File HandlesltSTDINgtRead from standard input (keyboard)ltSTDOUTgtPrint to standard output (screen)ltSTDERRgtFor outputting error messagesltARGVgtReads the names of the files from the

command line and opens them all

ARGV array contains the text after the programrsquos name in command line

ltARGVgt takes each file in turnIf there is nothing specified on the

command line it reads from the standard input

Since this is very commonly used Perl provides an abbreviation for ltARGVgtnamely lt gt

An example is shown

$lineno = 1while (lt gt) print $lineno ++print ldquo$lineno $_rdquoIn this program the name of the file has

to be given on the command lineperl list_linespl file1txtperl list_linespl atxt btxt ctxt

Control Structures

IntroductionThere are many control constructs in

PerlSimilar to those in CWould be illustrated through

examplesThe available constructs forforeachifelseifelsewhiledo etc

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 3: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

The lsquosplicersquo function

Arguments to the lsquosplicersquo functionThe first argument is an arrayThe second argument is an offset (index

number of the list element to begin splicing at)

Third argument is the number of elements to remove

colors = (ldquoredrdquo ldquogreenrdquo ldquobluerdquo ldquoblackrdquo)

middle = splice (colors 1 2) middle contains the elements removed

File Handling

Interacting with the user

Read from the keyboard (standard input)Use the file handle ltSTDINgtVery simple to useprint ldquoEnter your name rdquo$name = ltSTDINgt Read from

keyboardprint ldquoGood morning $name nrdquo$name also contains the newline

character Need to chop it off

The lsquochoprsquo FunctionThe lsquochoprsquo function removes the last

character of whatever it is given to chopIn the following example it chops the

newlineprint ldquoEnter your name rdquo chop ($name = ltSTDINgt) Read from keyboard and chop newlineprint ldquoGood morning $name nrdquolsquochoprsquo removes the last character

irrespective of whether it is a newline or not Sometimes dangerous

Safe chopping lsquochomp

The lsquochomprsquo function works similar to lsquochoprsquo with the difference that it chops off the last character only if it is a newline

print ldquoEnter your name rdquochomp ($name = ltSTDINgt) Read from keyboard and chomp newlineprint ldquoGood morning $name nrdquo

File Operations

Opening a file The lsquoopenrsquo command opens a file and

returns a file handleFor standard input we have a

predefined handle ltSTDINgt$fname = ldquohomeisgreporttxtrdquo

while (ltXYZgt) print ldquoLine number $ $_rdquo

open XYZ $fname

Checking the error code$fname = ldquohomeisgreporttxtrdquoopen XYZ $fname or die ldquoError in open $rdquowhile (ltXYZgt) print ldquoLine number $ $_rdquo$ returns the line number (starting at 1)$_ returns the contents of last match$ returns the error codemessage

Reading from a file

The last example also illustrates file reading

The angle brackets (lt gt) are the line input operators

The data read goes into $_

Writing into a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogt$outrdquo or die ldquoError in write

$rdquofor $i (120) print XYZ ldquo$i Hello the time isrdquo

scalar(localtime) ldquonrdquo

Appending to a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogtgt$outrdquo or die ldquoError in

write $rdquofor $i (120) print XYZ ldquo$i Hello the time

isrdquoscalar(localtime) ldquonrdquo

Closing a file

where XYZ is the file handle of the file being closed

close XYZ

Printing a file

This is very easy to do in Perl $input = ldquohomeisgreporttxtrdquo open IN $input or die ldquoError in

open $rdquowhile (ltINgt) printclose IN

Command Line Arguments

Perl uses a special array called ARGVList of arguments passed along with the

script name on the command lineExample if you invoke Perl as perl testpl red blue green then ARGV

will be (red blue green)Printing the command line argumentsforeach (ARGV) print ldquo$_ nrdquo

Standard File HandlesltSTDINgtRead from standard input (keyboard)ltSTDOUTgtPrint to standard output (screen)ltSTDERRgtFor outputting error messagesltARGVgtReads the names of the files from the

command line and opens them all

ARGV array contains the text after the programrsquos name in command line

ltARGVgt takes each file in turnIf there is nothing specified on the

command line it reads from the standard input

Since this is very commonly used Perl provides an abbreviation for ltARGVgtnamely lt gt

An example is shown

$lineno = 1while (lt gt) print $lineno ++print ldquo$lineno $_rdquoIn this program the name of the file has

to be given on the command lineperl list_linespl file1txtperl list_linespl atxt btxt ctxt

Control Structures

IntroductionThere are many control constructs in

PerlSimilar to those in CWould be illustrated through

examplesThe available constructs forforeachifelseifelsewhiledo etc

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 4: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

File Handling

Interacting with the user

Read from the keyboard (standard input)Use the file handle ltSTDINgtVery simple to useprint ldquoEnter your name rdquo$name = ltSTDINgt Read from

keyboardprint ldquoGood morning $name nrdquo$name also contains the newline

character Need to chop it off

The lsquochoprsquo FunctionThe lsquochoprsquo function removes the last

character of whatever it is given to chopIn the following example it chops the

newlineprint ldquoEnter your name rdquo chop ($name = ltSTDINgt) Read from keyboard and chop newlineprint ldquoGood morning $name nrdquolsquochoprsquo removes the last character

irrespective of whether it is a newline or not Sometimes dangerous

Safe chopping lsquochomp

The lsquochomprsquo function works similar to lsquochoprsquo with the difference that it chops off the last character only if it is a newline

print ldquoEnter your name rdquochomp ($name = ltSTDINgt) Read from keyboard and chomp newlineprint ldquoGood morning $name nrdquo

File Operations

Opening a file The lsquoopenrsquo command opens a file and

returns a file handleFor standard input we have a

predefined handle ltSTDINgt$fname = ldquohomeisgreporttxtrdquo

while (ltXYZgt) print ldquoLine number $ $_rdquo

open XYZ $fname

Checking the error code$fname = ldquohomeisgreporttxtrdquoopen XYZ $fname or die ldquoError in open $rdquowhile (ltXYZgt) print ldquoLine number $ $_rdquo$ returns the line number (starting at 1)$_ returns the contents of last match$ returns the error codemessage

Reading from a file

The last example also illustrates file reading

The angle brackets (lt gt) are the line input operators

The data read goes into $_

Writing into a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogt$outrdquo or die ldquoError in write

$rdquofor $i (120) print XYZ ldquo$i Hello the time isrdquo

scalar(localtime) ldquonrdquo

Appending to a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogtgt$outrdquo or die ldquoError in

write $rdquofor $i (120) print XYZ ldquo$i Hello the time

isrdquoscalar(localtime) ldquonrdquo

Closing a file

where XYZ is the file handle of the file being closed

close XYZ

Printing a file

This is very easy to do in Perl $input = ldquohomeisgreporttxtrdquo open IN $input or die ldquoError in

open $rdquowhile (ltINgt) printclose IN

Command Line Arguments

Perl uses a special array called ARGVList of arguments passed along with the

script name on the command lineExample if you invoke Perl as perl testpl red blue green then ARGV

will be (red blue green)Printing the command line argumentsforeach (ARGV) print ldquo$_ nrdquo

Standard File HandlesltSTDINgtRead from standard input (keyboard)ltSTDOUTgtPrint to standard output (screen)ltSTDERRgtFor outputting error messagesltARGVgtReads the names of the files from the

command line and opens them all

ARGV array contains the text after the programrsquos name in command line

ltARGVgt takes each file in turnIf there is nothing specified on the

command line it reads from the standard input

Since this is very commonly used Perl provides an abbreviation for ltARGVgtnamely lt gt

An example is shown

$lineno = 1while (lt gt) print $lineno ++print ldquo$lineno $_rdquoIn this program the name of the file has

to be given on the command lineperl list_linespl file1txtperl list_linespl atxt btxt ctxt

Control Structures

IntroductionThere are many control constructs in

PerlSimilar to those in CWould be illustrated through

examplesThe available constructs forforeachifelseifelsewhiledo etc

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 5: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Interacting with the user

Read from the keyboard (standard input)Use the file handle ltSTDINgtVery simple to useprint ldquoEnter your name rdquo$name = ltSTDINgt Read from

keyboardprint ldquoGood morning $name nrdquo$name also contains the newline

character Need to chop it off

The lsquochoprsquo FunctionThe lsquochoprsquo function removes the last

character of whatever it is given to chopIn the following example it chops the

newlineprint ldquoEnter your name rdquo chop ($name = ltSTDINgt) Read from keyboard and chop newlineprint ldquoGood morning $name nrdquolsquochoprsquo removes the last character

irrespective of whether it is a newline or not Sometimes dangerous

Safe chopping lsquochomp

The lsquochomprsquo function works similar to lsquochoprsquo with the difference that it chops off the last character only if it is a newline

print ldquoEnter your name rdquochomp ($name = ltSTDINgt) Read from keyboard and chomp newlineprint ldquoGood morning $name nrdquo

File Operations

Opening a file The lsquoopenrsquo command opens a file and

returns a file handleFor standard input we have a

predefined handle ltSTDINgt$fname = ldquohomeisgreporttxtrdquo

while (ltXYZgt) print ldquoLine number $ $_rdquo

open XYZ $fname

Checking the error code$fname = ldquohomeisgreporttxtrdquoopen XYZ $fname or die ldquoError in open $rdquowhile (ltXYZgt) print ldquoLine number $ $_rdquo$ returns the line number (starting at 1)$_ returns the contents of last match$ returns the error codemessage

Reading from a file

The last example also illustrates file reading

The angle brackets (lt gt) are the line input operators

The data read goes into $_

Writing into a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogt$outrdquo or die ldquoError in write

$rdquofor $i (120) print XYZ ldquo$i Hello the time isrdquo

scalar(localtime) ldquonrdquo

Appending to a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogtgt$outrdquo or die ldquoError in

write $rdquofor $i (120) print XYZ ldquo$i Hello the time

isrdquoscalar(localtime) ldquonrdquo

Closing a file

where XYZ is the file handle of the file being closed

close XYZ

Printing a file

This is very easy to do in Perl $input = ldquohomeisgreporttxtrdquo open IN $input or die ldquoError in

open $rdquowhile (ltINgt) printclose IN

Command Line Arguments

Perl uses a special array called ARGVList of arguments passed along with the

script name on the command lineExample if you invoke Perl as perl testpl red blue green then ARGV

will be (red blue green)Printing the command line argumentsforeach (ARGV) print ldquo$_ nrdquo

Standard File HandlesltSTDINgtRead from standard input (keyboard)ltSTDOUTgtPrint to standard output (screen)ltSTDERRgtFor outputting error messagesltARGVgtReads the names of the files from the

command line and opens them all

ARGV array contains the text after the programrsquos name in command line

ltARGVgt takes each file in turnIf there is nothing specified on the

command line it reads from the standard input

Since this is very commonly used Perl provides an abbreviation for ltARGVgtnamely lt gt

An example is shown

$lineno = 1while (lt gt) print $lineno ++print ldquo$lineno $_rdquoIn this program the name of the file has

to be given on the command lineperl list_linespl file1txtperl list_linespl atxt btxt ctxt

Control Structures

IntroductionThere are many control constructs in

PerlSimilar to those in CWould be illustrated through

examplesThe available constructs forforeachifelseifelsewhiledo etc

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 6: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

The lsquochoprsquo FunctionThe lsquochoprsquo function removes the last

character of whatever it is given to chopIn the following example it chops the

newlineprint ldquoEnter your name rdquo chop ($name = ltSTDINgt) Read from keyboard and chop newlineprint ldquoGood morning $name nrdquolsquochoprsquo removes the last character

irrespective of whether it is a newline or not Sometimes dangerous

Safe chopping lsquochomp

The lsquochomprsquo function works similar to lsquochoprsquo with the difference that it chops off the last character only if it is a newline

print ldquoEnter your name rdquochomp ($name = ltSTDINgt) Read from keyboard and chomp newlineprint ldquoGood morning $name nrdquo

File Operations

Opening a file The lsquoopenrsquo command opens a file and

returns a file handleFor standard input we have a

predefined handle ltSTDINgt$fname = ldquohomeisgreporttxtrdquo

while (ltXYZgt) print ldquoLine number $ $_rdquo

open XYZ $fname

Checking the error code$fname = ldquohomeisgreporttxtrdquoopen XYZ $fname or die ldquoError in open $rdquowhile (ltXYZgt) print ldquoLine number $ $_rdquo$ returns the line number (starting at 1)$_ returns the contents of last match$ returns the error codemessage

Reading from a file

The last example also illustrates file reading

The angle brackets (lt gt) are the line input operators

The data read goes into $_

Writing into a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogt$outrdquo or die ldquoError in write

$rdquofor $i (120) print XYZ ldquo$i Hello the time isrdquo

scalar(localtime) ldquonrdquo

Appending to a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogtgt$outrdquo or die ldquoError in

write $rdquofor $i (120) print XYZ ldquo$i Hello the time

isrdquoscalar(localtime) ldquonrdquo

Closing a file

where XYZ is the file handle of the file being closed

close XYZ

Printing a file

This is very easy to do in Perl $input = ldquohomeisgreporttxtrdquo open IN $input or die ldquoError in

open $rdquowhile (ltINgt) printclose IN

Command Line Arguments

Perl uses a special array called ARGVList of arguments passed along with the

script name on the command lineExample if you invoke Perl as perl testpl red blue green then ARGV

will be (red blue green)Printing the command line argumentsforeach (ARGV) print ldquo$_ nrdquo

Standard File HandlesltSTDINgtRead from standard input (keyboard)ltSTDOUTgtPrint to standard output (screen)ltSTDERRgtFor outputting error messagesltARGVgtReads the names of the files from the

command line and opens them all

ARGV array contains the text after the programrsquos name in command line

ltARGVgt takes each file in turnIf there is nothing specified on the

command line it reads from the standard input

Since this is very commonly used Perl provides an abbreviation for ltARGVgtnamely lt gt

An example is shown

$lineno = 1while (lt gt) print $lineno ++print ldquo$lineno $_rdquoIn this program the name of the file has

to be given on the command lineperl list_linespl file1txtperl list_linespl atxt btxt ctxt

Control Structures

IntroductionThere are many control constructs in

PerlSimilar to those in CWould be illustrated through

examplesThe available constructs forforeachifelseifelsewhiledo etc

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 7: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Safe chopping lsquochomp

The lsquochomprsquo function works similar to lsquochoprsquo with the difference that it chops off the last character only if it is a newline

print ldquoEnter your name rdquochomp ($name = ltSTDINgt) Read from keyboard and chomp newlineprint ldquoGood morning $name nrdquo

File Operations

Opening a file The lsquoopenrsquo command opens a file and

returns a file handleFor standard input we have a

predefined handle ltSTDINgt$fname = ldquohomeisgreporttxtrdquo

while (ltXYZgt) print ldquoLine number $ $_rdquo

open XYZ $fname

Checking the error code$fname = ldquohomeisgreporttxtrdquoopen XYZ $fname or die ldquoError in open $rdquowhile (ltXYZgt) print ldquoLine number $ $_rdquo$ returns the line number (starting at 1)$_ returns the contents of last match$ returns the error codemessage

Reading from a file

The last example also illustrates file reading

The angle brackets (lt gt) are the line input operators

The data read goes into $_

Writing into a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogt$outrdquo or die ldquoError in write

$rdquofor $i (120) print XYZ ldquo$i Hello the time isrdquo

scalar(localtime) ldquonrdquo

Appending to a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogtgt$outrdquo or die ldquoError in

write $rdquofor $i (120) print XYZ ldquo$i Hello the time

isrdquoscalar(localtime) ldquonrdquo

Closing a file

where XYZ is the file handle of the file being closed

close XYZ

Printing a file

This is very easy to do in Perl $input = ldquohomeisgreporttxtrdquo open IN $input or die ldquoError in

open $rdquowhile (ltINgt) printclose IN

Command Line Arguments

Perl uses a special array called ARGVList of arguments passed along with the

script name on the command lineExample if you invoke Perl as perl testpl red blue green then ARGV

will be (red blue green)Printing the command line argumentsforeach (ARGV) print ldquo$_ nrdquo

Standard File HandlesltSTDINgtRead from standard input (keyboard)ltSTDOUTgtPrint to standard output (screen)ltSTDERRgtFor outputting error messagesltARGVgtReads the names of the files from the

command line and opens them all

ARGV array contains the text after the programrsquos name in command line

ltARGVgt takes each file in turnIf there is nothing specified on the

command line it reads from the standard input

Since this is very commonly used Perl provides an abbreviation for ltARGVgtnamely lt gt

An example is shown

$lineno = 1while (lt gt) print $lineno ++print ldquo$lineno $_rdquoIn this program the name of the file has

to be given on the command lineperl list_linespl file1txtperl list_linespl atxt btxt ctxt

Control Structures

IntroductionThere are many control constructs in

PerlSimilar to those in CWould be illustrated through

examplesThe available constructs forforeachifelseifelsewhiledo etc

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 8: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

File Operations

Opening a file The lsquoopenrsquo command opens a file and

returns a file handleFor standard input we have a

predefined handle ltSTDINgt$fname = ldquohomeisgreporttxtrdquo

while (ltXYZgt) print ldquoLine number $ $_rdquo

open XYZ $fname

Checking the error code$fname = ldquohomeisgreporttxtrdquoopen XYZ $fname or die ldquoError in open $rdquowhile (ltXYZgt) print ldquoLine number $ $_rdquo$ returns the line number (starting at 1)$_ returns the contents of last match$ returns the error codemessage

Reading from a file

The last example also illustrates file reading

The angle brackets (lt gt) are the line input operators

The data read goes into $_

Writing into a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogt$outrdquo or die ldquoError in write

$rdquofor $i (120) print XYZ ldquo$i Hello the time isrdquo

scalar(localtime) ldquonrdquo

Appending to a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogtgt$outrdquo or die ldquoError in

write $rdquofor $i (120) print XYZ ldquo$i Hello the time

isrdquoscalar(localtime) ldquonrdquo

Closing a file

where XYZ is the file handle of the file being closed

close XYZ

Printing a file

This is very easy to do in Perl $input = ldquohomeisgreporttxtrdquo open IN $input or die ldquoError in

open $rdquowhile (ltINgt) printclose IN

Command Line Arguments

Perl uses a special array called ARGVList of arguments passed along with the

script name on the command lineExample if you invoke Perl as perl testpl red blue green then ARGV

will be (red blue green)Printing the command line argumentsforeach (ARGV) print ldquo$_ nrdquo

Standard File HandlesltSTDINgtRead from standard input (keyboard)ltSTDOUTgtPrint to standard output (screen)ltSTDERRgtFor outputting error messagesltARGVgtReads the names of the files from the

command line and opens them all

ARGV array contains the text after the programrsquos name in command line

ltARGVgt takes each file in turnIf there is nothing specified on the

command line it reads from the standard input

Since this is very commonly used Perl provides an abbreviation for ltARGVgtnamely lt gt

An example is shown

$lineno = 1while (lt gt) print $lineno ++print ldquo$lineno $_rdquoIn this program the name of the file has

to be given on the command lineperl list_linespl file1txtperl list_linespl atxt btxt ctxt

Control Structures

IntroductionThere are many control constructs in

PerlSimilar to those in CWould be illustrated through

examplesThe available constructs forforeachifelseifelsewhiledo etc

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 9: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Checking the error code$fname = ldquohomeisgreporttxtrdquoopen XYZ $fname or die ldquoError in open $rdquowhile (ltXYZgt) print ldquoLine number $ $_rdquo$ returns the line number (starting at 1)$_ returns the contents of last match$ returns the error codemessage

Reading from a file

The last example also illustrates file reading

The angle brackets (lt gt) are the line input operators

The data read goes into $_

Writing into a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogt$outrdquo or die ldquoError in write

$rdquofor $i (120) print XYZ ldquo$i Hello the time isrdquo

scalar(localtime) ldquonrdquo

Appending to a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogtgt$outrdquo or die ldquoError in

write $rdquofor $i (120) print XYZ ldquo$i Hello the time

isrdquoscalar(localtime) ldquonrdquo

Closing a file

where XYZ is the file handle of the file being closed

close XYZ

Printing a file

This is very easy to do in Perl $input = ldquohomeisgreporttxtrdquo open IN $input or die ldquoError in

open $rdquowhile (ltINgt) printclose IN

Command Line Arguments

Perl uses a special array called ARGVList of arguments passed along with the

script name on the command lineExample if you invoke Perl as perl testpl red blue green then ARGV

will be (red blue green)Printing the command line argumentsforeach (ARGV) print ldquo$_ nrdquo

Standard File HandlesltSTDINgtRead from standard input (keyboard)ltSTDOUTgtPrint to standard output (screen)ltSTDERRgtFor outputting error messagesltARGVgtReads the names of the files from the

command line and opens them all

ARGV array contains the text after the programrsquos name in command line

ltARGVgt takes each file in turnIf there is nothing specified on the

command line it reads from the standard input

Since this is very commonly used Perl provides an abbreviation for ltARGVgtnamely lt gt

An example is shown

$lineno = 1while (lt gt) print $lineno ++print ldquo$lineno $_rdquoIn this program the name of the file has

to be given on the command lineperl list_linespl file1txtperl list_linespl atxt btxt ctxt

Control Structures

IntroductionThere are many control constructs in

PerlSimilar to those in CWould be illustrated through

examplesThe available constructs forforeachifelseifelsewhiledo etc

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 10: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Reading from a file

The last example also illustrates file reading

The angle brackets (lt gt) are the line input operators

The data read goes into $_

Writing into a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogt$outrdquo or die ldquoError in write

$rdquofor $i (120) print XYZ ldquo$i Hello the time isrdquo

scalar(localtime) ldquonrdquo

Appending to a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogtgt$outrdquo or die ldquoError in

write $rdquofor $i (120) print XYZ ldquo$i Hello the time

isrdquoscalar(localtime) ldquonrdquo

Closing a file

where XYZ is the file handle of the file being closed

close XYZ

Printing a file

This is very easy to do in Perl $input = ldquohomeisgreporttxtrdquo open IN $input or die ldquoError in

open $rdquowhile (ltINgt) printclose IN

Command Line Arguments

Perl uses a special array called ARGVList of arguments passed along with the

script name on the command lineExample if you invoke Perl as perl testpl red blue green then ARGV

will be (red blue green)Printing the command line argumentsforeach (ARGV) print ldquo$_ nrdquo

Standard File HandlesltSTDINgtRead from standard input (keyboard)ltSTDOUTgtPrint to standard output (screen)ltSTDERRgtFor outputting error messagesltARGVgtReads the names of the files from the

command line and opens them all

ARGV array contains the text after the programrsquos name in command line

ltARGVgt takes each file in turnIf there is nothing specified on the

command line it reads from the standard input

Since this is very commonly used Perl provides an abbreviation for ltARGVgtnamely lt gt

An example is shown

$lineno = 1while (lt gt) print $lineno ++print ldquo$lineno $_rdquoIn this program the name of the file has

to be given on the command lineperl list_linespl file1txtperl list_linespl atxt btxt ctxt

Control Structures

IntroductionThere are many control constructs in

PerlSimilar to those in CWould be illustrated through

examplesThe available constructs forforeachifelseifelsewhiledo etc

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 11: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Writing into a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogt$outrdquo or die ldquoError in write

$rdquofor $i (120) print XYZ ldquo$i Hello the time isrdquo

scalar(localtime) ldquonrdquo

Appending to a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogtgt$outrdquo or die ldquoError in

write $rdquofor $i (120) print XYZ ldquo$i Hello the time

isrdquoscalar(localtime) ldquonrdquo

Closing a file

where XYZ is the file handle of the file being closed

close XYZ

Printing a file

This is very easy to do in Perl $input = ldquohomeisgreporttxtrdquo open IN $input or die ldquoError in

open $rdquowhile (ltINgt) printclose IN

Command Line Arguments

Perl uses a special array called ARGVList of arguments passed along with the

script name on the command lineExample if you invoke Perl as perl testpl red blue green then ARGV

will be (red blue green)Printing the command line argumentsforeach (ARGV) print ldquo$_ nrdquo

Standard File HandlesltSTDINgtRead from standard input (keyboard)ltSTDOUTgtPrint to standard output (screen)ltSTDERRgtFor outputting error messagesltARGVgtReads the names of the files from the

command line and opens them all

ARGV array contains the text after the programrsquos name in command line

ltARGVgt takes each file in turnIf there is nothing specified on the

command line it reads from the standard input

Since this is very commonly used Perl provides an abbreviation for ltARGVgtnamely lt gt

An example is shown

$lineno = 1while (lt gt) print $lineno ++print ldquo$lineno $_rdquoIn this program the name of the file has

to be given on the command lineperl list_linespl file1txtperl list_linespl atxt btxt ctxt

Control Structures

IntroductionThere are many control constructs in

PerlSimilar to those in CWould be illustrated through

examplesThe available constructs forforeachifelseifelsewhiledo etc

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 12: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Appending to a file

$out = ldquohomeisgouttxtrdquoopen XYZ ldquogtgt$outrdquo or die ldquoError in

write $rdquofor $i (120) print XYZ ldquo$i Hello the time

isrdquoscalar(localtime) ldquonrdquo

Closing a file

where XYZ is the file handle of the file being closed

close XYZ

Printing a file

This is very easy to do in Perl $input = ldquohomeisgreporttxtrdquo open IN $input or die ldquoError in

open $rdquowhile (ltINgt) printclose IN

Command Line Arguments

Perl uses a special array called ARGVList of arguments passed along with the

script name on the command lineExample if you invoke Perl as perl testpl red blue green then ARGV

will be (red blue green)Printing the command line argumentsforeach (ARGV) print ldquo$_ nrdquo

Standard File HandlesltSTDINgtRead from standard input (keyboard)ltSTDOUTgtPrint to standard output (screen)ltSTDERRgtFor outputting error messagesltARGVgtReads the names of the files from the

command line and opens them all

ARGV array contains the text after the programrsquos name in command line

ltARGVgt takes each file in turnIf there is nothing specified on the

command line it reads from the standard input

Since this is very commonly used Perl provides an abbreviation for ltARGVgtnamely lt gt

An example is shown

$lineno = 1while (lt gt) print $lineno ++print ldquo$lineno $_rdquoIn this program the name of the file has

to be given on the command lineperl list_linespl file1txtperl list_linespl atxt btxt ctxt

Control Structures

IntroductionThere are many control constructs in

PerlSimilar to those in CWould be illustrated through

examplesThe available constructs forforeachifelseifelsewhiledo etc

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 13: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Closing a file

where XYZ is the file handle of the file being closed

close XYZ

Printing a file

This is very easy to do in Perl $input = ldquohomeisgreporttxtrdquo open IN $input or die ldquoError in

open $rdquowhile (ltINgt) printclose IN

Command Line Arguments

Perl uses a special array called ARGVList of arguments passed along with the

script name on the command lineExample if you invoke Perl as perl testpl red blue green then ARGV

will be (red blue green)Printing the command line argumentsforeach (ARGV) print ldquo$_ nrdquo

Standard File HandlesltSTDINgtRead from standard input (keyboard)ltSTDOUTgtPrint to standard output (screen)ltSTDERRgtFor outputting error messagesltARGVgtReads the names of the files from the

command line and opens them all

ARGV array contains the text after the programrsquos name in command line

ltARGVgt takes each file in turnIf there is nothing specified on the

command line it reads from the standard input

Since this is very commonly used Perl provides an abbreviation for ltARGVgtnamely lt gt

An example is shown

$lineno = 1while (lt gt) print $lineno ++print ldquo$lineno $_rdquoIn this program the name of the file has

to be given on the command lineperl list_linespl file1txtperl list_linespl atxt btxt ctxt

Control Structures

IntroductionThere are many control constructs in

PerlSimilar to those in CWould be illustrated through

examplesThe available constructs forforeachifelseifelsewhiledo etc

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 14: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Printing a file

This is very easy to do in Perl $input = ldquohomeisgreporttxtrdquo open IN $input or die ldquoError in

open $rdquowhile (ltINgt) printclose IN

Command Line Arguments

Perl uses a special array called ARGVList of arguments passed along with the

script name on the command lineExample if you invoke Perl as perl testpl red blue green then ARGV

will be (red blue green)Printing the command line argumentsforeach (ARGV) print ldquo$_ nrdquo

Standard File HandlesltSTDINgtRead from standard input (keyboard)ltSTDOUTgtPrint to standard output (screen)ltSTDERRgtFor outputting error messagesltARGVgtReads the names of the files from the

command line and opens them all

ARGV array contains the text after the programrsquos name in command line

ltARGVgt takes each file in turnIf there is nothing specified on the

command line it reads from the standard input

Since this is very commonly used Perl provides an abbreviation for ltARGVgtnamely lt gt

An example is shown

$lineno = 1while (lt gt) print $lineno ++print ldquo$lineno $_rdquoIn this program the name of the file has

to be given on the command lineperl list_linespl file1txtperl list_linespl atxt btxt ctxt

Control Structures

IntroductionThere are many control constructs in

PerlSimilar to those in CWould be illustrated through

examplesThe available constructs forforeachifelseifelsewhiledo etc

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 15: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Command Line Arguments

Perl uses a special array called ARGVList of arguments passed along with the

script name on the command lineExample if you invoke Perl as perl testpl red blue green then ARGV

will be (red blue green)Printing the command line argumentsforeach (ARGV) print ldquo$_ nrdquo

Standard File HandlesltSTDINgtRead from standard input (keyboard)ltSTDOUTgtPrint to standard output (screen)ltSTDERRgtFor outputting error messagesltARGVgtReads the names of the files from the

command line and opens them all

ARGV array contains the text after the programrsquos name in command line

ltARGVgt takes each file in turnIf there is nothing specified on the

command line it reads from the standard input

Since this is very commonly used Perl provides an abbreviation for ltARGVgtnamely lt gt

An example is shown

$lineno = 1while (lt gt) print $lineno ++print ldquo$lineno $_rdquoIn this program the name of the file has

to be given on the command lineperl list_linespl file1txtperl list_linespl atxt btxt ctxt

Control Structures

IntroductionThere are many control constructs in

PerlSimilar to those in CWould be illustrated through

examplesThe available constructs forforeachifelseifelsewhiledo etc

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 16: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Standard File HandlesltSTDINgtRead from standard input (keyboard)ltSTDOUTgtPrint to standard output (screen)ltSTDERRgtFor outputting error messagesltARGVgtReads the names of the files from the

command line and opens them all

ARGV array contains the text after the programrsquos name in command line

ltARGVgt takes each file in turnIf there is nothing specified on the

command line it reads from the standard input

Since this is very commonly used Perl provides an abbreviation for ltARGVgtnamely lt gt

An example is shown

$lineno = 1while (lt gt) print $lineno ++print ldquo$lineno $_rdquoIn this program the name of the file has

to be given on the command lineperl list_linespl file1txtperl list_linespl atxt btxt ctxt

Control Structures

IntroductionThere are many control constructs in

PerlSimilar to those in CWould be illustrated through

examplesThe available constructs forforeachifelseifelsewhiledo etc

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 17: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

ARGV array contains the text after the programrsquos name in command line

ltARGVgt takes each file in turnIf there is nothing specified on the

command line it reads from the standard input

Since this is very commonly used Perl provides an abbreviation for ltARGVgtnamely lt gt

An example is shown

$lineno = 1while (lt gt) print $lineno ++print ldquo$lineno $_rdquoIn this program the name of the file has

to be given on the command lineperl list_linespl file1txtperl list_linespl atxt btxt ctxt

Control Structures

IntroductionThere are many control constructs in

PerlSimilar to those in CWould be illustrated through

examplesThe available constructs forforeachifelseifelsewhiledo etc

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 18: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

$lineno = 1while (lt gt) print $lineno ++print ldquo$lineno $_rdquoIn this program the name of the file has

to be given on the command lineperl list_linespl file1txtperl list_linespl atxt btxt ctxt

Control Structures

IntroductionThere are many control constructs in

PerlSimilar to those in CWould be illustrated through

examplesThe available constructs forforeachifelseifelsewhiledo etc

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 19: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Control Structures

IntroductionThere are many control constructs in

PerlSimilar to those in CWould be illustrated through

examplesThe available constructs forforeachifelseifelsewhiledo etc

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 20: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

IntroductionThere are many control constructs in

PerlSimilar to those in CWould be illustrated through

examplesThe available constructs forforeachifelseifelsewhiledo etc

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 21: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Concept of BlockA statement block is a sequence of

statements enclosed in matching pair of and

if (year == 2000) print ldquoYou have entered new

milleniumnrdquoBlocks may be nested within other

blocks

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 22: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Definition of TRUE in Perlbull In Perl only three things areconsidered as FALSE1048766The value 01048766The empty string (ldquo rdquo)1048766undefbull Everything else in Perl is TRUE

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 23: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

if elsebull General syntaxif (test expression) if TRUE do thiselse if FALSE do this

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 24: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Examplesif ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo else print ldquoYou are somebody else nrdquoif ($flag == 1) print ldquoThere has been an error nrdquo The else block is optional

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 25: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

elseifbull Exampleprint ldquoEnter your id rdquochomp ($name = ltSTDINgt) if ($name eq lsquoisgrsquo) print ldquoWelcome Indranil nrdquo elseif ($name eq lsquobkdrsquo) print ldquoWelcome Bimal nrdquo elseif ($name eq lsquoakmrsquo) print ldquoWelcome Arun nrdquo else print ldquoSorry I do not know you nrdquo

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 26: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Sort the elements in numerical order

num = qw (10 2 5 22 7 15)

new = sort $a lt=gt $b num

Write a Perl program segment to sort an array in the descending order

new = sort $a lt=gt $b num

new = reverse new

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 27: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

What is the difference between the functions

lsquochoprsquo and lsquochomprsquo

ldquochoprdquo removes the last character in a string ldquochomprdquo does the same but only if the last character is the newline character

Write a Perl program segment to read a textfile ldquoinputtxtrdquo and generate as output another file ldquoouttxtrdquo where a line number precedes all the lines

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 28: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

open INP ldquoinputtxtrdquo or die ldquoError in open $rdquo

open OUT ldquogt$outtxtrdquo or die ldquoError in write$rdquo

while (ltINPgt)

print OUT ldquo$ $_rdquo

close INP

close OUT

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 29: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

What is the significance of the file handle

ltARGVgt

It reads the names of files from the command line and opens them all (reads line by line)

How can you exit a loop in Perl based on

some condition

Using the ldquolastrdquo keyword

last if (i gt 10)

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 30: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

String Functions

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 31: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

The Split Function lsquo splitrsquo is used to split a string into multiple pieces using a

delimiter and create a list out of it $_=lsquoRedBlueGreenWhite255 details = split $_ foreach (details) print ldquo$_nrdquo The first parameter to lsquosplitrsquo is a regular expression that specifies

what to split on The second specifies what to split

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 32: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Another example

$_= ldquosateesh satteeshgmailcom 283493rdquo

($name $email $phone) = split $_

By default lsquosplitrsquo breaks a string using space as delimiter

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 33: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

The Join Function

lsquojoinrsquo is used to concatenate several elements into a single string with a specified delimiter in between

$new = join $x1 $x2 $x3 $x4 $x5 $x6

$sep = lsquorsquo

$new = join $sep $x1 $x2 $w3 abc $x4 $x5

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 34: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Regular Expressions

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 35: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Introduction

One of the most useful features of Perl

What is a regular expression (RegEx)

-Refers to a pattern that follows the rules of syntax

-Basically specifies a chunk of text

-Very powerful way to specify string patterns

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 36: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

An Example without RegEx$found = 0

$_ = ldquoHello good morning everybodyrdquo

$search = ldquoeveryrdquo

foreach $word (split)

if ($word eq $search)

$found = 1

last

if ($found)

print ldquoFound the word lsquoeveryrsquo nrdquo

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 37: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Using RegEx$_ = ldquoHello good morning everybodyrdquo

if ($_ =~ every)

print ldquoFound the word lsquoeveryrsquo nrdquo

bull Very easy to use

bull The text between the forward slashes defines the regular expression

bull If we use ldquo~rdquo instead of ldquo=~rdquo it means that the pattern is not present in the string

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 38: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

The previous example illustrates literal texts as regular expressions Simplest form of regular expression

Point to remember

When performing the matching all the characters in the string are considered to be significant including punctuation and white spaces

For example every will not match in the previous example

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 39: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Another Simple Example$_ = ldquoWelcome to SRI NIDHI studentsrdquo

if (SRI NIDHI)

print ldquorsquoSRI NIDHIrsquo is present in the stringnrdquo

if (toSRI NIDHI)

print ldquoThis will not matchnrdquo

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 40: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Types of RegExBasically two types

Matching

Checking if a string contains a substring

The symbol lsquomrsquo is used (optional if forward slash used as delimiter)

Substitution

Replacing a substring by another substring

The symbol lsquosrsquo is used

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 41: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Matching

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 42: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

The =~ OperatorTells Perl to apply the regular expression on the

right to the value on the left

The regular expression is contained within delimiters (forward slash by default)

If some other delimiter is used then a preceding lsquomrsquo is essential

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 43: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Examples$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ day)

print ldquoMatch successful n

bull Both forms are equivalent

bull The lsquomrsquo in the first form is optional

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 44: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

$string = ldquoGood dayrdquo

if ($string =~ mday)

print ldquoMatch successful n

if ($string =~ m[day[ )

print ldquoMatch successful n

bull Both forms are equivalent

bull The character following lsquomrsquo is the delimiter

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 45: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Character ClassUse square brackets to specify ldquoany value in the list of possible

valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [0123456789])

print found a number n

if ($string =~ [aeiou])

print Found a vowel n

if ($string =~ [0123456789ABCDEF])

print Found a hex digit n

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 46: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Character Class NegationUse lsquo^rsquo at the beginning of the character class to

specify ldquoany single element that is not one of these valuesrdquo

my $string = ldquoSome test string 1234

if ($string =~ [^aeiou])

print Found a consonantn

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 47: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Pattern AbbreviationsUseful in common cases

S Not a space character

W Not a word character

D Not a digit same as [^0-9]

s A space character (tab space etc)

w A word character [0-9a-zA-Z_]

d A digit same as [0-9]

Anything except newline

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 48: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

$string = ldquoGood and bad days

if ($string =~ ds)

print Found something like daysn

if ($string =~ wwwws)

print Found a four-letter wordn

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 49: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

AnchorsThree ways to define an anchor

^ anchors to the beginning of string

$ anchors to the end of the string

b anchors to a word boundary

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 50: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

if ($string =~ ^w)

does string start with a word character

if ($string =~ d$)

does string end with a digit

if ($string =~ bGoodb)

Does string contain the word ldquoGoodrdquo

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 51: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

MultipliersThere are three multiplier characters

Find zero or more occurrences

+ Find one or more occurrences

Find zero or one occurrence

Some example usages

$string =~ ^w+

$string =~ d

$string =~ bw+s+

$string =~ w+s$

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 52: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Substitution

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 53: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Basic UsageUses the lsquosrsquo character

Basic syntax is

$new =~ spattern_to_matchnew_pattern

What this does Looks for pattern_to_match in $new and if found replaces it

with new_patternIt looks for the pattern once That is only the first occurrence

is replacedThere is a way to replace all occurrences

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 54: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Examples$xyz = ldquoRama and Lakshman went to the forestrdquo

$xyz =~ sLakshmanBharat

$xyz =~ sRw+aBharat

$xyz =~ s[aeiou]i

$abc = ldquoA year has 11 months nrdquo

$abc =~ sd+12

$abc =~ s n$

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 55: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Common ModifiersTwo such modifiers are defined

i ignore case

g matchsubstitute all occurrences

$string = ldquoRam and Shyam are very honest

if ($string =~ RAMi)

print ldquoRam is present in the stringrdquo

$string =~ smjg

Ram -gt Raj Shyam -gt Shyaj

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 56: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Use of Memory in RegExWe can use parentheses to capture a piece of

matched text for later usePerl memorizes the matched textsMultiple sets of parentheses can be used

How to recall the captured textUse 1 2 3 etc if still in RegExUse $1 $2 $3 if after the RegEx

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 57: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Examples$string = ldquoRam and Shyam are honest

$string =~ ^(w+)

print $1 n

prints ldquoRanrdquo

$string =~ (w+)$

print $1 n

prints ldquostnrdquo

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 58: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

$string = ldquoRam and Shyam are very poor

if ($string =~ (w)1)

print found 2 in a rown

if ($string =~ (w+)1)

print found repeatn

$string =~ s(w+) and (w+)$2 and $1

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 59: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Example 1validating user input

print ldquoEnter age (or q to quit)

chomp (my $age = ltSTDINgt)

exit if ($age =~ ^q$i)

if ($age =~ D)

print $age is a non-numbern

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 60: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Example 2 validation contdFile has 2 columns name and age delimited by one or

more spaces Can also have blank lines or commented lines (start with )

open IN $file or die Cannot open $file $

while (my $line = ltINgt)

chomp $line

next if ($line =~ ^s$ or $line =~ ^s)

my ($name $age) = split s+ $line

print ldquoThe age of $name is $age n

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 61: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Some Special Variables

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 62: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

$amp $` and $rsquoWhat is $amp

It represents the string matched by the last successful pattern match

What is $`

It represents the string preceding whatever was matched by the last successful pattern match

What is $lsquo

It represents the string following whatever was matched by the last successful pattern match

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 63: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Example

$_ = abcdefghi

def

print $`$amp$n

prints abcdefghi

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 64: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

So actually hellip

S` represents pre match

$amp represents present match

$rsquo represents post match

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 65: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Data structures in Perl

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 66: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

The following example defines a sample perl array of arrays

tgs = (

[article series sed amp awk troubleshooting vim bash]

[ebooks linux 101 vim 101 nagios core bash 101 ])

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 67: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

To access a single element for example to Access 2nd element from the 1st array do the following

$tgs[0][1]

Access all the elements one by one as shown below

foreach ( tgs )

print ldquo$_n

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101

Page 68: Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Perl Hash of Hashestags = ( articles =gt vim =gt 20 awesome articles posted

awk =gt 9 awesome articles posted

sed =gt 10 awesome articles posted

ebooks =gt linux 101 =gt Practical Examples to Build a Strong Foundation in Linux

nagios core =gt Monitor Everything Be Proactive and Sleep Well

)

To access a single element from hash do the following

print $tagsebookslinux 101