Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: regex on a line

by arturo (Vicar)
on Aug 01, 2002 at 16:28 UTC ( [id://186825]=note: print w/replies, xml ) Need Help??


in reply to regex on a line

First: literal parens need to be escaped, or they'll be seen as grouping operators. Your input has literal parentheses in it, so you need to take note of that.

Second: Since you can capture more than one match in a regular expression, you need to pay attention to which match you want to grab. When, in your second pattern match, you set $view to $1, you're nabbing what's in the first parentheses, which in this case is what $target is already set to. You either want to get rid of the parentheses around that first \w+ so it doesn't capture, or use $2 to capture what you want. Of course you need to make sure you're taking account of the first point I made above.

Third: note that the minus sign is not a word character, so given your example and what you say you want to capture, you should be using a slightly more complicated regex than (\w+). You need to match word characters and the minus sign, so the natural choice is a character class : [\w\-] (the - must be escaped because it has special meaning inside a character class).

Fourth: you're printing both target and view outside of your conditional. That's not likely to lead to sensible output, since those things are only set if your regular expressions match.

Fifth, and I'll leave this as an exercise for you, there's a more efficient way to do this than match things twice. Use the power of list assignment with your regex matches and capturing parentheses, here's a sample of how that works:

$_ ="I have a lovely bunch of bananas"; if ( my ($verb, $adjective, $fruit) = /^I (\w+) a (\w+) \w+ of (\w+)/ +) { print "It would seem your $fruit, which you describe as '$adjectiv +e', is something you $verb.\n"; }

The inner block (the "if") here is only executed if the pattern matches, so if you put something like that inside your loop, it will be quite efficient, since you only try to match once instead of twice.

HTH

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://186825]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2024-04-25 19:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found