-1

I am new to perl and need some help. I have two text files I am trying to read from. I don't understand where I need to place these files in order to be able to access them with the code. If someone would walk me through the steps that would be great. I'm using windows 8, notepad++ is my text editor and I'm executing everything from the command prompt. Please don't give me an absurdly technical answer. Dumb it down for me! Thanks!

my $file = 'filename.txt';
open my $info, $file or die "could not open this $file";
  • Check [What's a path?](https://en.wikipedia.org/wiki/Path_(computing)) and [Perl 101 - Working with files](http://perl101.org/files.html) – LaintalAy May 03 '16 at 20:01

1 Answers1

0

If you're simply using "filename.txt" as the filename, the file should be in the same folder as your program.

You have an error in your syntax. It should be

my $file = 'filename.txt';
open(my $filehandle, "<", $file) or die "Could not open file $file. Error: $!";

Having opened the file, bear in mind there are different ways of reading from it. Sometimes you might want to read it a line at a time, in which case the syntax would be something like this:

while (my $line = <$filehandle>) {
   chomp $line;
   print "$line\n";
}

Sometimes you might want to read the entire file into one variable, in which case the syntax would be something like this:

my $file = "filename.txt";
my $document = do {
    local $/ = undef;
    open my $filehandle, "<", $file
        or die "could not open $file: $!";
    <$filehandle>;
};

(see this question for more info)

Notwithstanding the amount of information available, seemingly simple things like this can be frustrating when you're learning a new language. You won't regret learning Perl if you stick with it. And remember the Perl motto: TMTOWTDI :-)

Community
  • 1
  • 1
Frank H.
  • 876
  • 11
  • 21
  • 2
    Frank, nicely said. Cody, I'll just leave this here for you: http://perldoc.perl.org/perlopentut.html (I think you'll find it worth 20 minutes of your time to better understand how perl handles files.) – jgreve May 03 '16 at 22:05
  • 1
    Pedantically, if you're just using 'filename.txt', then the file should be in whatever is the current directory at that time. That will probably be the same directory as the program, but it's not guaranteed. – Dave Cross May 06 '16 at 14:22