Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Please advise how I can fetch something on one line and the next line. I have tried many versions and cant seem to fetch both. Here is the information I need to get but they are on two lines.
myword nextLine
Here is what I have tried along with at least 20 other attempts but cant get it to work:
open(TMPFILE,"<main.html"); while (<TMPFILE>) { if ($_ =~ /myword\s+nextLine/) #ALSO tried: if ($_ =~ /myword\nnextLine/) # if ($_ =~ /myword\\nnextLine/) { print "$_\n"; } } close TMPFILE;

Replies are listed 'Best First'.
Re: Two lines Regular Expression
by hardburn (Abbot) on Jun 09, 2003 at 17:47 UTC

    You're only reading one line at a time. Your choices are:

    1. Slurp the entire file into a scalar (such as with my $in = join('', <TMPLFILE>);). This could potentially take a lot of memory
    2. Read in the next line manually ($_ .= <TMPLFILE>;) at the top of your while loop.

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    Note: All code is untested, unless otherwise stated

      Thanks that works now how do I get that match to print outside of the while loop?? I tried something using $data but no luck:
      open(TMPFILE,"<main.html"); while (<TMPFILE>) { chomp; my $data; my $in = join('',<TMPFILE>); if ($in =~ /(myword)\s+nextLine/) { print "Match = " . $1; $data = $1; } } print $data #I want this to print my match results here on myword # so it should print "myword" here but it doesnt.
        It looks like your $data is out of scope. I would recommend use strict; it would have given you an error. Move the my $data; before the the while loop if you want to print afterwards.
Re: Two lines Regular Expression
by pzbagel (Chaplain) on Jun 09, 2003 at 17:48 UTC

    How about:

    while(<TMPFILE>) { if (/myword/) { $_.=<TMPFILE>; print; } }

    Basically, if the current line matches read and append the next line and print. The while loop only reads one line at a time(unless you change $/), so the nextline will just not be in $_ in your code, you have to read it in when you match myword.

    HTH