Your problem is that you're putting all the text into $text and then making your while loop while($line = $text). But since $text is just a simple variable, the while loop will only execute once, with $line equal to the whole text (that is, all the lines). Then inside the loop, you're using $line as if it will magically get the next line, instead of keeping the same value. How best to proceed depends on how you're getting your data into the program. The easiest way would be if you're reading it from standard in, or from a file (or, as in the sample code I'll show here, from the special DATA filehandle), because then you can loop over it. Otherwise, you'll want to split it into an array of lines first with split "\n", $text.
#!/usr/bin/perl use strict; use warnings; my $expa = "A"; #title element which appears before every #sentence my $expb = "B"; #the regexp I'm loooking for my $s; while (<DATA>){ chomp; if (/$expa/){ $s = $_; chomp($_ = <DATA>); if (/$expb/){ print "$s\n\t$_\n\n\n"; } } } __DATA__ A This is a title of the first sentence some text here containing the element B I need and more text here A This is a title of the second sentence C some text here but no element I need so it should be ignored A This is a title for the third sentence last sentence with the element B that I'm looking for
I'm trying to keep your logic mostly the same, though I'm not sure I entirely understand it. If you're reading from a file, substitute the filehandle for DATA (or if you want the default, you can just use <>.

In reply to Re: RegExp Loop by Eimi Metamorphoumai
in thread RegExp Loop by ramigi

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.