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

I'd like to do something such as: print <CHUNK>; --but have it only print one line at a time, not the whole file. And I don't want to use a
while (<CHUNK>) { print $_; }
I just want one line, then the next line later as I need it for whatever I am printing. Is there another way of doing this other than reading the file into an array and then using array elements as needed? Does it exist, what I am looking for?

Replies are listed 'Best First'.
Re: To print one line from a file? Non-loop?
by broquaint (Abbot) on May 24, 2002 at 12:48 UTC
    You need to put the filehandle read into a scalar context to get a single line at a time, as by default print() is evaluated in a list context
    print scalar <DATA>; __DATA__ the first line the second line
    This will output "the first line". Or if you decide you need to put the file into an array I'd recommend using Dominus' Tie::File module.
    HTH

    _________
    broquaint

Re: To print one line from a file? Non-loop?
by Molt (Chaplain) on May 24, 2002 at 12:40 UTC

    Err.. have you tried doing print <chunk>; as you said? Just that should work, providing you with the first line and allowing you to get the rest later. I often use this to read things like headers, before while'ing away to read the rest.

    Update: Listen to Broquaint's advice below, I forgot print worked in a list context for a moment. Sorry, mental slip.

Re: To print one line from a file? Non-loop?
by Nakko (Initiate) on May 24, 2002 at 12:51 UTC
    Okay, now I have a username and stuff. Yay! No, when I do print <CHUNK>; it prints the whole dern file. It's a typical text file, just some HTML code I want a piece at a time, and I fill in the middle. I assume that it's because, like, when you assign an array equal to a filehandle, it throws all the lines into separate elements, but if you assign a scalar equal to a filehandle, it just grabs one line. So, since print accepts a list, it goes ahead and gives it a list. The whole file. Is it normally supposed to work the other way? It sure doesn't do that for me. Or, am I crazy?