budsz
budsz

Reputation: 21

Continue with newline in perl

I have perl script like this:

elsif ($url =~ m/^(http|https):\/\/(banner(s?)|advertising|iklan|adsbox|adserver|adservice(s?))\.(.*)/) {
        print "http:\/\/ip\.mdm\-lo\-00\.willsz\.net/null\.png\n";
}

That working for redirect squid (one line), but if change to multiline like this, absolutely not working.

elsif ($url =~ m/^(http|https):\/\/(banner(s?) \
 |advertising \
 |iklan \
 |adsbox \
 |adserver \
 |adservice(s?))\.(.*)/) {
    print "http:\/\/ip\.mdm\-lo\-00\.willsz\.net/null\.png\n";
}

Any suggestion? - Thank You

Upvotes: 2

Views: 222

Answers (2)

Borodin
Borodin

Reputation: 126722

You are getting a little carried away with your escapes and parentheses! And it is much simpler to change the delimiter to something like {...} that isn't in the body of the pattern; then you don't have to escape the slashes

Unless you use the /x modifier, all whitespace is significant in a regex pattern, including newlines, and escaping them makes no difference at all. This isn't C!

You should also use non-capturing parentheses like (?:...) unless you need to capture substrings of the matched pattern

And there is no need for a throw-away .* to match the tail of the string, unless you need to match and capture it for further use

Your best option is to use m{...}x. Then you can add spaces, tabs, and newlines as you like to make the pattern clearer

And backslashes aren't necessary in double-quoted strings at all, unless you want to add special characters like \t for tab, \n for newline etc.

This code should do what you want

elsif ( $url =~ m{ ^ https?:// (?:
        banners?    |
        advertising |
        iklan       |
        adsbox      |
        adserver    |
        adservices? ) \. }x ) {

    print "http://ip.mdm-lo-00.willsz.net/null.png\n";
}

Upvotes: 5

mamod
mamod

Reputation: 514

if ($url =~ m{
    ^(?:http|https)://(?:banners?|
    advertising|
    iklan|
    adsbox|
    adserver|
    adservices?)\.
}x #<---- x for multi line regex
){
    print "http://ip.mdm-lo-00.willsz.net/null.png\n";
}

Upvotes: 1

Related Questions