Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

File slurping into $text and then accessing a specific line?

by legend (Sexton)
on Feb 26, 2008 at 21:55 UTC ( [id://670411]=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://670411]
Approved by toolic
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (2)
As of 2024-04-26 02:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found