You are on page 1of 14

Matching exact occurrences using { and }

 Using {}, we can match exactly the no. of occurrences for a particular
pattern.
Ex:
A{3}: exactly 3 occurrences of ‘A’
A{2,5}: min 2 occurrences and max 5 occurrences of ‘A’
A{2,}: min 2 occurrences and max is not defined.

Ex: Program to validate a date

Reusing a pattern
 We can reuse a pattern with out re-writing it along the length of a string.
 The pattern to be reused must be enclosed in parantheses. Then, it will
be stored in memory.
 To reuse it, we can use special escape sequences like \1, \2 and so on.
 \1 reuses the first pattern stored in memory, \2 reuses the second one
and so on.

Pattern matching variables

 These are used to use the data that matches with a pattern in the rest of
the program.
 $1 stores the first value that matches with a pattern, $2 matches the
second value and so on.
 $& matches the whole pattern that is matched.
Specifying a different delimiter
 We can choose a different character as delimiter, other than / /
 To specify a different delimiter, we need to use ‘m’ option followed by
the chosen symbols used as delimiters.
Pattern matching options

 i: to ignore case
 g: searches for a pattern globally, i.e any where in the string.
 o: evaluates a pattern only once.
Search and replace

 ‘s’ option can be used to not only search for a pattern, but also to
replace it with any other pattern.
Syntax:
s/pattern1/pattern2/options
Options:
 i: ignore case
 g: replace all occurrences of a pattern
Remove leading and trailing spaces from the contents of a file

open(F1,"mytext.txt");
open(F2,">mytext2.txt");

do
{
$line=<F1>;
chop($line);
$line=~s/^[ \t]+//;
$line=~s/[ \t]+$//;
$line=~s/\b[ \t]+/ /;
print F2 $line,"\n";
}while($line ne "");

close(F1);
close(F2);

print `cp mytext2.txt mytext.txt`;

unlink("mytext2.txt");
‘tr’ operator

 Translates one character with another i.e one-to-one substitution.


Syntax:
tr/char_set1/char_set2/options
options:
 c: translate all characters, except the ones that are specified.
 d: deletes the set of characters from the input line
:wq

You might also like