Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re^2: how to read multiple lines from a file

by skyworld_chen (Acolyte)
on Apr 13, 2013 at 05:05 UTC ( [id://1028482]=note: print w/replies, xml ) Need Help??


in reply to Re: how to read multiple lines from a file
in thread how to read multiple line from a file

thanks Athanasus. The way you provide is good, but if I want to search a special word across several lines within a file, for example, if a line contains a word "one" and the line next to it contains a word "two", this "tie" seems not as good as I expect. anyway, thanks for your idea

  • Comment on Re^2: how to read multiple lines from a file

Replies are listed 'Best First'.
Re^3: how to read multiple lines from a file
by Athanasius (Archbishop) on Apr 13, 2013 at 06:08 UTC

    Hello skyworld_chen,

    The solutions by 2teez and TJPride below are good ones, but if you want to adapt my Tie::File approach, just use a sliding window:

    #! perl use strict; use warnings; use Tie::File; my $filename = 'data.txt'; tie my @lines, 'Tie::File', $filename or die "Cannot tie file '$filena +me': $!"; my @search_words = ('jumped', 'over'); for (0 .. $#lines - 1) { if ($lines[$_ ] =~ /$search_words[0]/ && $lines[$_ + 1] =~ /$search_words[1]/) { print "\nFound '$search_words[0]' on line ", ($_ + 1), ", and '$search_words[1]' on line ", ($_ + 2), "\n"; last; } } untie @lines;

    Output:

    16:02 >perl 605_SoPW.pl Found 'jumped' on line 5, and 'over' on line 6 16:03 >perl 605_SoPW.pl

    Your precise requirements are not clear (to me), but this technique can be easily adapted as needed.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (6)
As of 2024-04-26 09:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found