develooper Front page | perl.tips | Postings from August 2001

Perl Tip 4: Alternative quote characters 2, regular expressions

From:
Ask Bjoern Hansen
Date:
August 19, 2001 22:29
Subject:
Perl Tip 4: Alternative quote characters 2, regular expressions
Message ID:
Pine.BSF.4.21.0108192227450.38215-100000@onion.valueclick.com

If you didn't see the previous "alternative quote characters" tip,
then please read it now. It's available at
http://archive.develooper.com/daily-tips@perl.org/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 daily-tips-unsubscribe@perl.org
To subscribe: mail daily-tips-subscribe@perl.org
Or visit: http://learn.perl.org/tips/
Comments, suggestions? Send them to ask@perl.org.




nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About