Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Matching words

by graff (Chancellor)
on Feb 27, 2022 at 18:17 UTC ( [id://11141678]=note: print w/replies, xml ) Need Help??


in reply to Matching words

Here's another way, basically a variant of what roboticus posted (the key point being to use an array to keep the target words in one easily maintained place). This one uses a single capturing regex to handle all terms at once, and reports the hits instead of the misses:
use strict; use warnings; my @required = qw( name timestamp dl_retransmits_pct dl_throughput mac + ); my $req_regx = join( '|', @required ); while (my $line = <DATA>) { my %matched = map{ $_ => undef } $line =~ /($req_regx)/g; print $line if scalar( keys %matched ) == scalar( @required ); } __DATA__ mac timestamp name dl_retransmits_pct dl_throughput is a hit mac timestamp name dl_retransmits_pct throughout is a miss name timestamp dl_retransmits_pct dl_throughput is a miss foo mac name dl_throughput name timestamp name dl_retransmits_pct mac +mac is a hit name timestamp dl_retransmits_pct is a miss dl_throughput is a miss
But as Fletch suggested, if your input is really JSON data, you should use a JSON parser and handle the input as the data structure that it really is.

(updated to fix grammar and spelling)

Replies are listed 'Best First'.
Re^2: Matching words
by AnomalousMonk (Archbishop) on Feb 27, 2022 at 22:38 UTC
    my $req_regx = join( '|', @required );

    This is ok for the "pure" words given in the example, but there may be trouble if naughty regex metacharacters like * + ? ( ) [ ] etc. infiltrate the word list. See haukex's article Building Regex Alternations Dynamically for a thorough discussion of this technique.


    Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (12)
As of 2024-04-16 07:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found