in reply to pattern matching
One quick way is to use the "?" modifier like so:
while (<>) { # Only require a non-null first capture if (/(\w\w)(\w\w)?(\w\w)?(\w\w)?/) { # Do something } }
In each of the captures, the "?" says that the item is optional. Therefore, the match will succeed if only the first capture succeeds.
Note that if you use warnings, you will still need to test each of the captures for null when you use them, to avoid getting uninitialized value warnings.
Update: bart's comment below about the whitespace is a good one. I think my solution will still work if you modify it slightly:
if (/(\s*\w\w)(\s+\w\w)?(\s+\w\w)?(\s+\w\w)?/) { # Do something }
Come to think of it, though, that just makes the whitespace part of the match, so ++bart, as his solution looks like a better one to do what you need.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: pattern matching
by bart (Canon) on Dec 25, 2006 at 18:54 UTC | |
by vineet2004 (Initiate) on Dec 26, 2006 at 04:38 UTC | |
by vineet2004 (Initiate) on Dec 26, 2006 at 07:23 UTC | |
by bart (Canon) on Dec 26, 2006 at 22:47 UTC |