2

I am working on a simple perl program for my first assignment in my programming class. I literally have been stuck on this first part for more than a day. I cannot get my program to simply open a text file that is in the same directory as the program.

#!/usr/bin/perl -w
use strict;

my($fileName, $line);

print "Please enter name of file to be opened: ", "\n";
$fileName = <STDIN>;
chop($fileName);

#Associates FILE filehandle with the file: "filename.txt"
open(FILE, $fileName) or die("Can't open '$fileName': $!");

while(my $line = <FILE>){
    print $line;
}

I am using strawberry perl. To run the program I am dragging and dropping the program into the command line to get the address of the program. It then attempts to run it.

It initially gave me a readline on closed filehandle error, and then I included the or die("Can't open '$fileName': $!"); portion of the code.

Now it says that there is no such file at the directory, but I know that the test.txt file is there because I just created it.

Picture of the code results: https://i.stack.imgur.com/dlK5g.jpg

File directory that shows locations of my files: https://i.stack.imgur.com/d3FSK.jpg)

tshepang
  • 12,111
  • 21
  • 91
  • 136
Jared
  • 391
  • 2
  • 6
  • 14
  • Are you sure you're in the right directory? `use Cwd; print getcwd(), "\n";` (Or just enter [`echo %cd% |`](http://stackoverflow.com/a/921762/132382) or `dir |` as your filename — but you should really use the [three-argument form of `open()`](http://perldoc.perl.org/functions/open.html) with an explicit MODE to prevent that kind of trick.) – pilcrow Nov 17 '13 at 21:34

2 Answers2

2

The prompt is showing C:\Users\jacjar\Documents as the current working directory

So this is where the program will look for test.txt

But it is not in that directory

text.txt is in L:\College\Junior Year\1st Semester\COSC 320 (Programming Languages)

Move your test.txt file to the C: path shown above and it will work

Vorsprung
  • 32,923
  • 5
  • 39
  • 63
  • to change the working directory in the cmd shell, use the cd command. To change the working directory in a perl script, use [chdir](http://perldoc.perl.org/functions/chdir.html) – ysth Nov 17 '13 at 22:47
  • Yeah, that's a unfortunately "feature" of Windows. It can be disabled, though. "Tools" | "Folder Options" | "View" | Uncheck "Hide Extensions for known file types" | "Apply" | "Apply to Folders" – ikegami Nov 17 '13 at 22:48
1

Do you realize you are trying to open C:\User\jacjar\Documents\test.txt?

ikegami
  • 367,544
  • 15
  • 269
  • 518