in reply to Reading from a file on a NT server

How do you know there are no problems opening the file? You aren't checking for errors at all! Please perldoc perlopentut and learn about the use of $! for error reporting.

Replies are listed 'Best First'.
Re: Re: Reading from a file on a NT server
by bwjen1 (Initiate) on Jan 30, 2003 at 15:40 UTC
    I am checking the return value of open() in my script. I removed this for simplicty when I asked for help. Below is my exact code for opening, reading and closing the file.

    $SaleFile="sales.csv"; # Print databases name print "DATABASE FILE: $SaleFile<br>\n"; # Check to see if database exists if (-e "$SaleFile"){print "FILE CHECK: $SaleFile does exist<br>\n"}els +e{print "FILE CHECK: ERROR: $SaleFile does NOT exist<br>\n";} # Open file for reading if (open(DAT,"$SaleFile") <= 0){print "ERROR: $SaleFile can't be opene +d<br>\n";}else{print "$SaleFile was opened successfully<br>\n";} # Read from database print <DAT>; @inFile=<DAT>; # Close database file if (close(DAT) <= 0) {print "ERROR: $SaleFile can't be closed<br>\n";} +else{print "$SaleFile was closed successfully<br>\n";} print "DATABASE SIZE: $#inFile<br>\n"; print "DATABASE: @inFile<br>\n";
    Cheers,

    Scotty

      Ok, a few comments:

      • Asking for help with code and then giving people different code probably isn't going to help uncover problems with the actual code. If you're not going to submit the actual code, pare the actual code down until you have the smallest chunk that exhibits the problem you're seeing.
      • Checking for the existance of a file and then opening it creates a race condition. Not as much of a problem in this case, but it's a well known way to introduce bugs (or worse, security problems). Just open the file, and if it fails and you really want to know why check if $! was POSIX::ENOENT
      • The usual idiom is open(...) or die "Can't open foo: $!\n"; you're possibly betraying a C heritage, but remember Perl isn't C.
      • $#array is the index of the last element, not the size. You mean print "Size: ", scalar @inFile, "\n"
      • Putting ""'s around a single scalar variable (e.g. "$SaleFile") is pretty much useless (except in the case where the scalar contains a blessed object with a custom stringification routine, but that's not the case here).

      ... # Read from database print <DAT>; @inFile=<DAT>;
      Erm ... you've already read the file and printed it to the screen. :-)

      Jenda