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!
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|