Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Grepping with Perl: How to stop after first match?

by Anonymous Monk
on Mar 21, 2013 at 23:09 UTC ( [id://1024838]=note: print w/replies, xml ) Need Help??


in reply to Grepping with Perl: How to stop after first match?

Why has nobody mentioned the ? delimiter for m and s?

I know this is several years too late to help the OP, but since it is coming up on top of a Google search, there must be a lot of people looking for something similar.

Answer: if you search with m?abc? or use s?abc?def? then IT WILL ONLY MATCH ONCE. The pattern can be reset to fire again with the

reset

operator. It is common to do that at end-of-file is you are processing many files and want to treat each one as a self-contained item to search. Further down is a sample of code showing this.

Without reading the full details of the OP's question (kind of pointless answering it exactly since it's so old) I think the OP should have had "state machines" explained to him. Since he was new to Perl but perhaps not programming in general, that might have been enough clue for him to realise how he might match patterns across multiple lines.

Following is a decent template which illustrates a simple state machine, and uses one-shot patterns:

my $state = 0; while(<>) { if($state == 0 && /CPU/) { $state = 1; } elsif($state == 1 && ?vendor?) { $state = 2; # YIPPEE! process the data } else { $state = 0; # fail } } continue { if(eof) { # do NOT put () on eof - RTFM close ARGV; # resets $. to start at 0 for the next file $state = 0; reset; } }

Of course, the state machine here actually takes over the task of matching only once, so the m?? is not strictly necessary here. If you didn't need to match across lines (let's say you're only looking for the first CPU) then you'd use m?CPU? and probably ignore the state machine functionality.

Another alternative (as mentioned) is "slurp"ing the contents, then multi-line patterns CAN be made to work with appropriate flags on the pattern. Once again, using m?? for the multi-line pattern will ensure it only works once (per file with reset), and the state machine wouldn't be needed in this example.

-- Andrew Clarke

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (10)
As of 2024-04-18 12:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found