cerr said:
I'm just trying to open a text file and print line by line.
My Code:
my $HANDLE = $filename;
open(HANDLE) or die("Could not open GPS source file.");
foreach $line (<HANDLE>) {
print $line;
print $client $line;
sleep(1);
}
close(HANDLE);
My Problem:
The script keeps dying on open().
The pernmissions of the file are set to -rw-r--r--
So what is the problem here? Not getting it...
Because your use of open() is completely broken. No kind of
open() function I have ever seen (as far as I remember) works
like that. All take a file name and return a handle that in
subsequent calls of functions to read from or write to the
file etc. is used. A handle is something very different from
the file's name (with the UNIX open() function it's an integer,
with C's fopen() function it's a pointer to some structure)
- and in Perl it's something you don't need to worry about;-)
And open() functions typically also take at least one more
argument that tells for what purpose the file is to be opened
for (i.e. for reading, writing or both - that makes a lot of a
difference when you have e.g. permission to read from but not
to write to the file) etc. And sometimes even additional flags
can or have to be given.
If you want a file opened for reading do
open my $handle, '<', $filename or die "Can't open file\n";
while ( my $line = <$handle> ) { ... }
close $handle;
The first argument to open() is the variable that, after a
successful call of open(), contains the handle for the file.
The second, '<', tells that you want it to be opened for
reading (use '>' for writing, but there are a number of
further possibilities, see 'perldoc -f open' for all the
gory details). And the third is the file name (or, with
other second arguments, it could be a program that then
gets run and from which you want to read its output or to
which you want to send data).
BTW, if I remember correctly, the difference between
for my $line ( <> ) { ... }
and
while ( my $line = <> ) { ... }
is that with 'for' the '<>' is used in list context, so the
whole file has to be read in immediately and thus stored in
memory as a whole. This normally doesn't make much sense.
With 'while' it gets read in line by line instead, so only
a single line has to be kept in memory.
Regards, Jens