Search code examples
perlparameter-passingfilenames

Perl : Cannot open a file with filename passed as argument


I am passing two filenames from a DOS batch file to a Perl script.

my $InputFileName = $ARGV[0];
my $OutputFileName = $ARGV[1];

Only the input file physically exists while the Outputfile must be created by the script.

open HANDLE, $OutputFileName or die $!;
open (HANDLE, ">$OutputFileName);
open HANDLE, ">$OutputFileName" or die $!;

All three fail.

However the following works fine.

open HANDLE, ">FileName.Txt" or die $!; 

What is the correct syntax?

Edit : Error message is : No such file or directory at Batchfile.pl at line nn


Solution

  • The proper way is to use the three-parameter form of open (with the mode as a separate parameter) with lexical file handles. Also die doesn't have a capital D.

    Like this

    open my $out, '>', $OutputFileName or die $!;
    

    but your last example should work assuming you have spelled die properly in your actual code.

    If you are providing a path to the filename that doesn't exist then you also need to create the intermediate directories.

    The die string will tell you the exact problem. What message do you get when this fails?