Perl Tip 4: Alternative quote characters 2, regular expressions
[email protected] (Ask Bjoern Hansen) Sun, 19 Aug 2001 22:28:01 -0700 (PDT)
| Newsgroups | perl.tips |
|---|---|
| Message-ID | <[email protected]> |
If you didn't see the previous "alternative quote characters" tip, then please read it now. It's available at http://archive.develooper.com/[email protected]/msg00003.html Just as we can make string scalars easier to read by using alternate quote characters, we can make regular expressions (regexps) easier on the eye too. One common thing that's umpleasant to write without alternate delimiters is matching a pathname or substituting one with another, for example: m/\/usr\/local\/bin\/foo/; s/\/usr\/local\/bin\/foo/\/some\/where\/else\/foo/; So let's do it in a neater way, by using !'s instead of /'es. m!/usr/local/bin/foo!; s!/usr/local/bin/foo!/some/where/else/foo!; In short, any non-alphanumeric, non-whitespace delimiter may replace the slashes, so it can be written as s^/usr/local/bin/foo^/some/where/else/foo^; too. Or even with #'s as the delimiter, but that's probably a bit too obscure to be useful, so don't tell anyone. ;-) If you use a character with a different "begin" and "end" character, like a ( or {, then the match works like this s{foo}{bar}; which then allows you to easily split the regexp (regular expression) on two lines, like $var =~ s{foo} {bar}; If it's a long regexp with only a few substitutions it can be a lot clearer written that way. For more information: see "perldoc perlre" and "perldoc perlop" and search for "Regexp Quote-Like Operators". You might also want to get the "Mastering Regular Expressions" book, which will teach you far more than you ever knew existed about regular expressions. It's a great book: http://learn.perl.org/books?isbn=1565922573 To unsubscribe: mail [email protected] To subscribe: mail [email protected] Or visit: http://learn.perl.org/tips/ Comments, suggestions? Send them to [email protected].