Substitution

 <  Day Day Up  >  

Just finding patterns in strings and lines of input isn't enough; sometimes you need to modify the data as well. One way ”but certainly not the only way ”is to use the substitution operator s/// . The syntax is as follows :

 s/  searchpattern  /  replacement  /; 

The substitution operator searches $_ by default for searchpattern and replaces the entire matched regular expression with replacement . The operator returns the number of matches or substitutions performed, or 0 if no matches were made. The following is an example:

 $_="Our house is in the middle of our street". s/middle/end/;         # Is now: Our house is in the end of our street s/in/at/;               # Is now: Our house is at the end of our street. if (s/apartment/condo/) {     #  This code isn't reached, see explanation. } 

Here, the substitutions happen as you would expect. The word middle is changed to end , and in is changed to at . The if statement, however, fails, because the word apartment does not appear in $_ and therefore can't be substituted.

The substitution operator can also use delimiters other than slashes ( / ), just as the match operator can. Simply put whatever delimiter you want immediately after the s , as shown here:

 s#street#avenue#; 

 <  Day Day Up  >  


SAMS Teach Yourself Perl in 24 Hours
Sams Teach Yourself Perl in 24 Hours (3rd Edition)
ISBN: 0672327937
EAN: 2147483647
Year: 2005
Pages: 241

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net