Cannot get file to be read.

L

Lalo Salvalus

I have a simple script that I can't get to read a file and am not sure
why.

Here's the script:
=============================================
use Getopt::Std;
getopts('d:hi:f:');

my @lines;

if ($opt_f) { readFile($opt_f)};

sub readFile {
my $filein = pop;
open (FIN, '< $filein' ) || die "cannot open file $filein, $!\n";
while ( <FIN> ) {
push @lines;
}
} # readFile

print "\@lines is @lines\n";
=============================================

When I run this from the command line I get "The system cannot find
the file specified." no matter if I have a copy of the file in the
same dir as the script, or if I specify a full path (with either
backslashes, forward slashes, or double back slashes), or if I specify
a relative path (with either backslashes, forward slashes, or double
back slashes):

C:\Perl>perl -w Test.pl -f myfile.txt
cannot open file myfile.txt, The system cannot find the file
specified.

I'm running ActivePerl 5.8.3 build 809 on Windows 2000.

All help is appreciated.

thanks,

Lalo
 
P

Paul Lalli

I have a simple script that I can't get to read a file and am not sure
why.

Here's the script:
=============================================
use Getopt::Std;
getopts('d:hi:f:');

my @lines;

if ($opt_f) { readFile($opt_f)};

sub readFile {
my $filein = pop;
open (FIN, '< $filein' ) || die "cannot open file $filein, $!\n";
^^^ ^^^

while ( <FIN> ) {
push @lines;
}
} # readFile

print "\@lines is @lines\n";
=============================================


Single quotes do not interpolate variable names. You're trying to open a
file literally named '$filein'. Change the ' to ".

Paul Lalli
 
T

Tore Aursand

sub readFile {
my $filein = pop;
open (FIN, '< $filein' ) || die "cannot open file $filein, $!\n";
while ( <FIN> ) {
push @lines;
}
} # readFile

1. Single quotes aren't interpolated; In the code above, you're trying to
open a file named '$filein'.

2. Why do you use 'pop' instead of 'shift' to get the input argument?

3. Why don't you close the file after reading it? And why do you iterate
over the lines in the file when the only thing you do is push'ing the
lines into an array?

my $lines = readFile( $opt_f );

sub readFile {
my $filein = shift;

open( FIN, '<', $filein ) or die "$!\n";
my @lines = <FIN>; # Beware of large files, though
close( FIN );

return \@lines;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,165
Latest member
JavierBrak
Top