0

I am trying to learn file handling in Perl, I want to open a .txt file located in D: drive on the terminal on Windows in read mode, so the code I am using is as:

open(DATA, "<D:/pay_info.txt") or die "Couldn't open file pay_info.txt, $!";
while(<DATA>) 
{ print "$_";}

it always shows

Couldn't open file pay_info.txt, No such file or directory at C:\perl\perl2.pl line 1.

what does it mean?

simbabque
  • 53,749
  • 8
  • 73
  • 136
  • 1
    It means what it says. That file doesn't exist. – simbabque Sep 25 '18 at 11:43
  • 3
    If you are just learning, you might want to read http://perldoc.perl.org/perlopentut.html. The style you used is very much outdated. If you are using a book or a tutorial, it is badly out of date. I suggest you take a look at [the Perl tag wiki here on Stack Overflow](https://stackoverflow.com/tags/perl/info), as it lists a lot of free high-quality up to date resources. – simbabque Sep 25 '18 at 11:45

2 Answers2

1

In a comment, you say:

I had to run with a space between < and D:/

Using the three-argument version of open would have avoided this issue. This has been the approach recommended in the Perl documentation for many years now.

open(my $fh, '<', 'D:/pay_info.txt')
  or die "Couldn't open file pay_info.txt, $!";

while (<$fh>) {
  print $_;
}

I've changed a few other things:

  • Used a lexical filehandle ($fh) instead of a global one (DATA). Actually, DATA is a special filehandle in Perl so it shouldn't be used for in most code.
  • Switched to using single quotes whenever possible (single-quoted strings recognise fewer special characters so it's a good idea to use them whenever possible).
  • Removed unnecessary quotes in your print line (actually, the $_ is optional there as well).
  • Light reformatting to make it more readable.
Dave Cross
  • 68,119
  • 3
  • 51
  • 97
0

Are you sure, that the file D:/pay_info.txt exists? Perl is unable to locate that file on the base folder of drive D: (that is the meaning of the error message printed by your die statement).

Frank Förster
  • 371
  • 1
  • 4
  • it worked, just I had to run with a space between < and D:/ – shanuj garg Sep 26 '18 at 18:39
  • Good to here, nevertheless you should read at least the perldoc document above mentioned by @simbebque. Usage of the suggested three parameter form would have avoided the error, is safer, and the state of the art way to open a file in perl. Do not forget to specify the encoding. – Frank Förster Sep 27 '18 at 06:59