What is the difference between
if ($URL !~ /^https?:\/\//i) {....}
and
if ($URL !~ m|^https?://|i) {....}
??
| SitePoint Sponsor |
What is the difference between
if ($URL !~ /^https?:\/\//i) {....}
and
if ($URL !~ m|^https?://|i) {....}
??
Ballot-Box.net - free polls for webmasters
Ravelly.com - free message board
FormLog.com - free form processor
perl allows you to use different delimiters with regexps. In the second regexp, '|' is used as the delimiter so the forward slashes in the pattern do not need escaping with a backslash. If you do not use the default delimiter '/' you have to put the regexp operator at the beginning of the regexp, in this case the "m".
| is a bad one to use though, in my opinion, as you'd then need to escape each pipe you'll use in your expression.
I also think / is a bad one because i find all the escaping of the / when doing urls or file paths makes it messy and difficult to understand.
I always use ! because i find it's very rare for me to have to escape the ! in the expression.
I'll show you what i mean about the above, we're going to do a v. basic check to see if a domain is google or yahoo. Using only regex ( a bad one at that ).
That was the pipe, notice we needed to escape the OR option between the 2 urls.Code:if($m =~ m|http://www.google.com/\|http://www.yahoo.com/|) {}
Personally i find the above confusing to read, especially if the person who is going to have to look at your code after isn;t that great at them in the first place.Code:if($m =~ m/http:\/\/www.google.com\/|http:\/\/www.yahoo.com\//) {}
Finally, 'my' version is very simple.
No escaping. So makes it much more readable.Code:if($m =~ m!http://www.google.com/|http://www.yahoo.com!) {}
Or am i wrong? Always willing to be taught differently.
Which delimiter to use depends on each situation. The pipe is maybe not the best choice because it is also a regexp meta character. And what is readable to one person is not as readable to the next person, that just comes down to personal choice to some extent. In this case:
the pipe is fine, it is a short regexp that isn't doing very much. If the regexp were changed later and a pipe was in the search pattern then the pipe would have to escaped or a different delimiter used.Code:if ($URL !~ m|^https?://|i) {....}
Bookmarks