View Single Post
Old 11-25-2003, 12:28 PM   #10 (permalink)
ratbastid
Darth Papa
 
ratbastid's Avatar
 
Location: Yonder
LTS Avoidance Mechanism #1: Alternate Delimiters

Why yes, my dear cheerios, there IS an easy way around LTS (Leaning Toothpick Syndrome).

Remember our basic regex operator, the "m//" operator? And how we can safely drop the "m" from it?

Well, here's the magic trick: ANY character after a lone "m", Perl will take to be the delimiter for a regular expression.

So the first line I wrote above:<pre>"2+2=5" =~ /2+2/;</pre>
could have been written:<pre>"2+2=5" =~ m|2+2|;</pre>
or:<pre>"2+2=5" =~ m"2+2";</pre>
You get the picture.

Here's the reason you'd do that. You only have to escape the fore-slash"/" character when you're using that as the delimiter. So if I wanted to know if a filename was in a particular directory, I could match like this:<pre>$filename =~ /\/usr\/local\/bin/;</pre>
Or I could just swap delimiters and not have to escape those slashes:<pre>$filename =~ m*/usr/local/bin*;</pre>

Ya dig? Just use a delimiter that won't show up in your pattern, and your escaping troubles get much easier to deal with.

This is helpful when you're trying to split pipe-delimited text data. It makes my eyes cross to say:<pre>my @values = split(/\|/, $line);</pre>
That "/\|/" construction is just painful. m'\|' is much better to me.
ratbastid is offline  
 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43