in reply to how to read multiple line from a file

One approach is to use the core module Tie::File. For example, if you have an input file “data.txt” containing:

the quick brown fox jumped over the unfortunate dog

Then this script:

#! 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': $!"; chomp(my @text = @lines[3 .. 5]); print "\n", join(' ', @text), "\n"; untie @lines;

will produce this output:

13:01 >perl 605_SoPW.pl fox jumped over 13:06 >

Hope that helps,

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

Replies are listed 'Best First'.
Re^2: how to read multiple lines from a file
by skyworld_chen (Acolyte) on Apr 13, 2013 at 05:05 UTC

    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

      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,