shanuj garg
shanuj garg

Reputation: 17

trying to open a file located in D drive on command prompt using perl

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?

Upvotes: 0

Views: 301

Answers (2)

Dave Cross
Dave Cross

Reputation: 69274

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.

Upvotes: 1

Frank F&#246;rster
Frank F&#246;rster

Reputation: 371

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).

Upvotes: 0

Related Questions