2. Find and Replace
• Thus far we have manipulated Perl RegEx’s Find feature but not it is
time to equip the Find and Replace functionality.
• Code: s/find/replace/
• Ex.
s/Godzilla/King Kong/; $temp =~ s/([a-z])/against $1’s team
• The find and replace functionality will only replace the first occurrence in the
string. In order to replace all occurrence you need to add a flag to mark it global.
• Code: g
• Ex. s/Godzilla/King Kong/g
3. s/// and m// similarities
• Create your own delimiters
• Ex. s/// s$$$ s%%%
• Ex. s//%% s@@** Can change individual groupings as long as pair is
consistent
• Substitution modifiers
• Flags i, x and s work, as well as them in combination with g
• Binding Operator
• Once again the default variable is checked against the s/// operator unless bound
to a different variable.
4. Case Shifting
• Sometimes when replacing a character or string you want it to be upper or lower case.
• Question: Why couldn’t you just place this in your search pattern?
• The following force the entire expression to shift their case:
• Forces all to uppercase
• Code: U s/(Jason|Frank)/U$1/gi;
• Forces all to lowercase
• Code: L
• Terminated the case shift in the middle of the expression
• Code: E
• The following force the following character to shift their case:
• Forces next character to uppercase
• Code: u
• Forces next character to lowercase
• Code: l
• ***Note: These escape sequence work in any string substitution as well not just find and replace.***
5. Updating Numerous Files
• We can update numerous files at once in Perl just like we used loops to
maneuver an entire directory in bash.
• In order to accomplish this there are 3 key items you need:
1. A way to get a file name – array, positional parameter, standard input
2. A backup file extension – temporary file for the update
3. The substitution – what to update
• The backup file type operator can be specified to any extension type you
want:
• Code : $^I
• Ex. $^I = “.bak”;
• Question: What type of loop should you use if your files are in an array?
6. Updating Numerous Files Example
#!/usr/bin/perl
use strict;
use warnings;
$^I = “.bak”;
While(<STDIN>)
{
s/^Author:.*/Author: Randal L. Schwartz/;
s/^Phone:.*n//;
s/^Date:.*/Date: $date/;
print;
}
Hinweis der Redaktion
Sometimes you are using a pattern fro the replace so if the pattern returns a lower or upper you might need to shift the case.