Forum Moderators: coopster & phranque

Message Too Old, No Replies

Opening a file with perl on local machine

         

dreaming of nascar

12:43 am on May 6, 2004 (gmt 0)

10+ Year Member



I am trying to write a program that will open a file and read it in PERL. I have done this serveral times before successfully, but not using my own computer to run the script. I have activePerl and Apache on my computer. Normal scripts run perfectly, but I would like to be able to read and write to a file. I have tried the regular

open(FILE, "file.txt");
@file = <FILE>;
close(FILE);
...
...

I then tried to see if the file exists using

if(-e @file){
print "File exists";
}
else{
print "File does not exist";
}

It always tells me that the file does not exist. What do I have to change or what am I doing wrong? Like I said, I have done this successfully many times, but not on my own computer. I am guessing that there is a slight change I have to make to run it on my computer. Thanks in advance!

D_O_N

VectorJ

1:21 am on May 6, 2004 (gmt 0)

10+ Year Member



You may want to try using the full path to the file rather than the relative path. Also, and I'm pretty sure this was just a typo, but to check for the existence of a file the line should be:

if (-e "file.txt") {

PhraSEOlogy

8:27 pm on May 6, 2004 (gmt 0)

10+ Year Member



D_O_N,

here is an example:

$/ = undef;
open (TEMP, "<file.txt");
$htmlt = <TEMP>;
close TEMP;

This reads all of the file into the $htmlt variable.

You appear to be trying to populate an array with one line of the file.

VectorJ

4:27 pm on May 7, 2004 (gmt 0)

10+ Year Member



Using the code

@html = <FILE>

is a syntactically correct way of populating an array with the entire file, one line per array element.

$/ is normally set to newline, so unsetting it just puts the entire file into a single scalar.

PhraSEOlogy

9:19 pm on May 13, 2004 (gmt 0)

10+ Year Member



VectorJ,

My example does suck the entire file into a scalar but then that is what I wanted.

I did not know you could read the entire file into an array using that syntax - Nice tip!

volatilegx

1:31 am on May 14, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Your best bet is to use the absolute path to the file... like this:

open(FILE, "/full/path/to/file/file.txt");
@file = <FILE>;
close(FILE);

or on Windows

open(FILE, "c:/full/path/to/file/file.txt");
@file = <FILE>;
close(FILE);