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

I am working on NT, and I'm trying to open a file. I write
open(FILE,"filename.txt"); $line=<FILE>; while ($line=<FILE>){ print $line; } close (FILE);
and it just doesn't work, it doesn't give any output (a blank page); I don't know why. Can you help me?

Thank you,
Tohar

Replies are listed 'Best First'.
Re: Opening files in NT
by Corion (Patriarch) on Sep 16, 2000 at 16:09 UTC

    Your problem is that you are not checking for errors. Always use the following idiom to open files :

    open FILE, "< $filename" or die "Couldn't open $filename : $!\n"; ... read file, do stuff ... close FILE;
    Not using "<" in the filename to specify a read operation also works, but it's better to be explicit in what you are doing.

    Another thing to watch out for is specifying DOS filenames in Perl, as Perl will interpolate strings if they are double-quoted (you use " instead of '). Instead of using a backslash ("\") to separate directories, use a forward slash ("/"). This works under both, Unix and DOS and relieves you from having to quote your backslashes in your sourcecode.

Re: Opening files in NT
by doran (Deacon) on Sep 19, 2000 at 09:22 UTC
    In addition to the good things Corion mentioned about always checking for errors when you make system calls and explicitly specifying "<" when opening files (even when you don't have to), I noticed a couple of other things.

    Because $line is a scalar variable, you are reading the file in line by line. Thus the first line is read in at the first instance of
    $line=<FILE>
    then the second line, and subsequent lines, are read in during the while() loop. With your code, the first line won't be printed. That may or may not be what you wanted.

    Finally, you'll probably need a carriage return and/or a line feed, so your print line should probably read something like
    print "$line\n\r";
    Again, this may or may not be what you want, but my experience with NT tells me the addition of a CR and/or LF often makes a difference.
      Actually, because $line hasn't been chomped, the newline will remain intact.