in reply to RegExp Loop

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 <>.