Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Reading from a file

by itzMe (Initiate)
on Aug 26, 2003 at 09:38 UTC ( #286634=perlquestion: print w/replies, xml ) Need Help??

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

Hi, I have just started working on PERL and am facing this problem. Is the implementation done like this? i have a text file sample.txt which has 3 lines
abc deg hij
when i read everything once i get all the details and then am not able 2 read it again. code used is
open(file1,"sample.txt"); print(<file1>); $line1=<file>; print($line1);
This does not print anything. Can u pls suggest?Have I done some mistake?
Thanks KP

Replies are listed 'Best First'.
Re: Reading from a file
by broquaint (Abbot) on Aug 26, 2003 at 10:13 UTC
    Firstly, it's always a good idea to check if the likes of open have succeeded e.g
    open(file1, "sample.txt") or die("ack - $!");
    Or you could always use the Fatal module to do that for you.

    Now on the second line you are reading the entire file into memory.

    This is because you are evaluating the filehandle readline operator in a list context, which (prototypes forbidding) is how all function arguments are evaluated, and in list context the filehandle readline operator will read until an eof has been reached. Now when you go to assign $line1 the filehandle file1 has read to the end of the file so returns nothing. Now if you want to get back to the beginning of the file then you'll need to use seek which sets the filehandle's pointer e.g
    seek(file1, 0, 0);
    However if you simply want to print a single line from file1 then you'll need to force scalar context which can be done using the scalar function e.g
    print scalar(<file1>);
    See. open, readline, eof, seek, scalar and the Input and output functions section of perlfunc for more info.


Re: Reading from a file
by CombatSquirrel (Hermit) on Aug 26, 2003 at 09:59 UTC
    The problem is that print is defined as print LIST (type perldoc -f print to see it) and therefore interprets <file1> not as a scalar, but an array whose contents are joined as they are printed. Because you can read files only sequentially, you are now at the end of the file and there is no more data. Workarounds:
    open(FILE, '<', 'sample.txt') or die "Could not open 'sample.txt' for +input: $!\n"; print scalar(<FILE>); # print ONE LINE from the file $line2 = <FILE>; # get ONE LINE from the file close FILE; print $line2; ### OR, alternatively open(FILE, '<', 'sample.txt') or die "Could not open 'sample.txt' for +input: $!\n"; print <FILE>; # print WHOLE FILE seek FILE, 0, 0; # go to beginning of file $line1 = <FILE>; # get ONE LINE from the file close FILE; print $line1;
    One tip: Always catch return values of system functions (such as open) or your program will do things that you don't want it to.
    Cheers, CombatSquirrel.
    Entropy is the tendency of everything going to hell.
Re: Reading from a file
by thinker (Parson) on Aug 26, 2003 at 09:56 UTC

    Hi itzMe,

    If you want to be able to access the contents of the file again after initially reading it, slurp it into an array. This is as simple as

    open FILE, "sample.txt" or die $!; my @lines = <file1>;

    Now you can use @lines in whatever way you want.

    Hope this helps


Re: Reading from a file
by castaway (Parson) on Aug 26, 2003 at 10:01 UTC
    There are a couple of possible mistakes:

    1. You don't check if the open() worked, and you're not passing it a full pathname to the file, are you sure it's found the file? Try using:

    open(file1, "sample.txt") || die "Can't open sample.txt ($!)";
    - the code will end (die) if the file cant be found or opened, including the '$!' will give you the system error message, such as 'cant find file' etc.

    2. You're using file1, whether the open actually worked or not. To get Perl to tell you if the file handle is actually readable, try putting 'use warnings;' at the top of your code.

    Do you realise that you are trying to print the first line of the file, then assign the second line to $line1, and then print that? Each line is read only once from the file handle, the next access will get the following line..


Re: Reading from a file
by bradcathey (Prior) on Aug 26, 2003 at 15:26 UTC
    For efficiency's sake, you can avoid the "slurping" by using a while loop to consider 1 line at a time.
    open... while (<file1>) { print; } close...
Re: Reading from a file
by Theo (Priest) on Aug 26, 2003 at 21:16 UTC
    All of the code examples shown close the file after using it. Your code didn't show that. Do you close the file?


Log In?

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2021-10-28 05:21 GMT
Find Nodes?
    Voting Booth?
    My first memorable Perl project was:

    Results (95 votes). Check out past polls.