Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: How to to search for an multiple words in a file using regular expressions

by Random_Walk (Prior)
on Oct 12, 2016 at 07:08 UTC ( [id://1173801]=note: print w/replies, xml ) Need Help??


in reply to How to to search for an multiple words in a file using regular expressions

A rough sketch to get you started. Not tested

# Hi all , I need a little help , I am new to perl If for example use strict; # A lot of help use warnings; # more help # in a file named out.txt open my $file, '<', 'out.txt' or die "My homework crashed: $!\n"; # And also print 0 if it doesn't find the word. # Make a note we did not find the word yet... my $found = 0; # which contains the following data Apple Banana potato / Ashok is a b +oy / Apple is good / aLL three sentences in three different lines while (my $line = <$file>) { # read the file line at a time in a loop my @words = split /\s+/, $line; # I need to search the first occurrence of apple and Ashok # Check if the line contains apple and Ashok. # Are these variable, or always the same two literals? # Does order matter? # If we did not find them on this line, use 'next' to check the ne +xt line next unless grep { $_ eq 'apple' } @words; # Oeps, not a regular e +xpression next unless grep { $_ eq 'Ashok' } @words; # # print the 3rd word in that line ie "potato", "a" . print $line[2]; # Why 2? :-) # Note we found the word $found = 1; # exit the loop last; } # if we did not find a word, tell the user print $found unless $found; # you may want to print a newline now ...

Cheers,
R.

Pereant, qui ante nos nostra dixerunt!
  • Comment on Re: How to to search for an multiple words in a file using regular expressions
  • Download Code

Replies are listed 'Best First'.
Re^2: How to to search for an multiple words in a file using regular expressions
by karlgoethebier (Abbot) on Oct 12, 2016 at 14:52 UTC
    "I've no doubt a friendly Nigerian Prince will fulfill the OP request in a short while."

    oiskuu at Re: Boyer Moore algorithm.

    «The Crux of the Biscuit is the Apostrophe»

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (8)
As of 2024-04-19 07:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found