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.sstatic.net/dlK5g.jpg

File directory that shows locations of my files: https://i.sstatic.net/d3FSK.jpg)

1
  • Are you sure you're in the right directory? use Cwd; print getcwd(), "\n"; (Or just enter echo %cd% | or dir | as your filename — but you should really use the three-argument form of open() with an explicit MODE to prevent that kind of trick.) Commented Nov 17, 2013 at 21:34

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

to change the working directory in the cmd shell, use the cd command. To change the working directory in a perl script, use chdir
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"
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.