Page 1 of 1

Perl substitution

Posted: Fri Jun 13, 2014 6:30 pm
by cah
One of Perl's strength is to substitute patterns in perl.

Nowadays, lots of web pages are created by applications. Some of them do not format the html well and one line could be extremely long with the same or similar pattern(s). In order to break them down, a substitute command in perl would help dramatically.

For example: Setting both $1 and $b to the following string:

Code: Select all

$a = $b = "a b c d a b c d a b c d a b";
Substitute pattern with the following regular expressions:

Code: Select all

$a =~ s/(.*) b c (.*)/\1\2/g;
$b =~ s/(.*?) b c (.*?)/\1\2/g;
Outcome:

Code: Select all

$a = a b c d a b c d ad a b
$b = ad ad ad a b
The first regular expression (.*) replaces the LAST pattern only (removes the last " b c " only from the string).
The second regular expression (.*?) replaces each pattern (removes all " b c " from the string).

/g means global to replace all occurrences of the pattern.