Professional Documents
Culture Documents
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.
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.
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);
unlink("mytext2.txt");
‘tr’ operator