ramya2005 has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks:

I want to create or write to a file in a specified directory. The following code fails during run time.
# uniqueCaptureName is supplied by another function return $uniqueCaptureName = 'C:/Program Files/PBORE/Public/Input/'."$uniqueCa +ptureName"; open $fh, ">$uniqueCaptureName" or die "can't open file \n";
Could some body point out the problem in above code!

Thanks.

Replies are listed 'Best First'.
Re: Create file in a specified directory
by ikegami (Patriarch) on Sep 01, 2005 at 18:16 UTC

    Print out $! to see the error message:

    open $fh, ">$uniqueCaptureName" or die "can't open file: $!\n";

    Better yet, use the three arg open:

    open $fh, '>', $uniqueCaptureName" or die "can't open file: $!\n";
      Thank you. The code was failing because I didn't have the directory named 'Input' under the 'Public'. When I created that directory it worked

      Is there a way to check the directory structure and create directories as specified in the path if it doesn't exist already?
        use -d (perldoc -f -X) to check for exsistence.. for making a directory there's perldoc -f mkdir, and for making it recursively there's mkpath in File::Path

        yes , sure you can check for that

        #check if the $dir does not exits then we create it if(!-d $dir){ mkdir($dir);}
        HTH
Re: Create file in a specified directory
by Old_Gray_Bear (Bishop) on Sep 01, 2005 at 18:18 UTC
    Change the text of your die message a trifle to include the $! (error message). I suspect that will give you a better feel for what is happening....
    open $fh, ">$uniqueCaptureName" or die "can't open file -- $! \n";

    ----
    I Go Back to Sleep, Now.

    OGB

Re: Create file in a specified directory
by sh1tn (Priest) on Sep 01, 2005 at 18:28 UTC
    You may want to use lexical scope in addition to strict, warnings, diagnistics
    pragmas and the good advices already given:
    open my $fh ...


Re: Create file in a specified directory
by InfiniteSilence (Curate) on Sep 01, 2005 at 18:46 UTC
    Hey, don't you mean,
    $uniqueCaptureName = 'C:\Program Files\PBORE\Public\Input\'."$uniqueCa +ptureName";

    ???

    Celebrate Intellectual Diversity

      I think backward slash is considered as escape sequence......
      Anyway, the problem is resolved now. I didn't have the specified directory created.
        I think backward slash is considered as escape sequence...... Anyway, the problem is resolved now. I didn't have the specified directory created.
        It is considered as a escape sequence but only in a double quoted string, in signle quoted strings it is treated as a regular backslash character.