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

thundergnat of this forum gave me an interesting program that looks like this:
use warnings; use strict; $/ = "_END=======\n"; while (<DATA>) { s/========KEYWORD.+\n//g; print '-' x 80, $_, '-' x 80; $text = $_; }
I was wondering if it is possible to access a particular line in the $text variable. I mean, once it has grabbed a chunk of data, I want to print a specific line from that. Is that possible by any chance?

Replies are listed 'Best First'.
Re: File slurping into $text and then accessing a specific line?
by Narveson (Chaplain) on Feb 26, 2008 at 22:40 UTC

    Yes, it is possible. But why are you slurping into $text?

    Slurping is recommended only if the presence of multiple lines of data in a single scalar somehow makes your task easier. Usually this is not the case.

    Far from showing us why you needed to slurp, you are asking how to access a particular line.

    use warnings; use strict; my $PARTICULAR_LINE; # regex print '-' x 80; while (<DATA>) { s/========KEYWORD.+\n//; print; if ( /$PARTICULAR_LINE/ ) { access($_) } } print '-' x 80; __DATA__

    This does the same printing job as the code you posted, and it accesses the particular line.

Re: File slurping into $text and then accessing a specific line?
by hipowls (Curate) on Feb 26, 2008 at 22:16 UTC

    Depending on how you decide on the particular line. There is

    my $line = ( split "\n", $_ )[$wanted_line];
    which splits $_ into a list and selects a line by number or
    my ($line) = /^(.*?PATTERN.*?)$/ms;
    which will pick a line on what PATTERN it conatins.

Re: File slurping into $text and then accessing a specific line?
by Prof Vince (Friar) on Feb 27, 2008 at 09:16 UTC
    If you want to access a line by its number, you might be interested in using Tie::File.