Perl substitution

Moderator: cah

Post Reply
cah
General of the Army / Fleet Admiral / General of the Air Force
General of the Army / Fleet Admiral / General of the Air Force
Posts: 1342
Joined: Sun Aug 17, 2008 5:05 am

Perl substitution

Post 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.
CAH, The Great
Post Reply