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

I have a snippet of code that doesn't seem to be working because of needing to change directories. In order to keep the program portable I don't want to specify the entire directory, just Current Directory -> Desired directory. The code is below, I've tried 'use Cwd;' and had no luck. Any help is appreciated although I'm sure the answer is very simple.
sub save{ print "Please specify a file name: "; chomp(my $file=uc<STDIN>); chomp(my $cwd = `pwd`); open ($file, "$cwd//Pandoras Box//>>$file.txt\n") || die "Could not sa +ve file: $!\n"; print $file "cont\n" || die "Could not write to file: $!\n"; print "File has been saved to Pandora's Box successfully!\n\n" || die +"Write fail: $!\n"; }

Replies are listed 'Best First'.
Re: Changing directories
by pc88mxer (Vicar) on May 07, 2008 at 17:56 UTC
    Update: The location of the perl script is available in $O. To get its directory, use dirname from the File::Basename module:
    use File::Basename qw(dirname); my $script_dir = dirname($0); my $path = "$script_dir/Pandoras Box/$file.txt"; ...

    Original response:

    The current working directory can always be referred to as . (a single dot), so there is no need to call the cwd command. It appears that you are just trying to do this:

    chomp(my $file =uc(<STDIN>)); my $path = "./Pandoras Box/$file.txt"; open FILE, '>>', $path or die "unable to append to $path: $!"; ...
    Note that the append mode designator '>>' comes before the path name (preferably as a separate argument), and I can't think of why you would need double forward slashes.

    Indeed, in this case specifing the current working directory with . is not even necessary:

    my $path = "Pandoras Box/$file.txt"; ...
Re: Changing directories
by TGI (Parson) on May 07, 2008 at 17:58 UTC

    I think you need to reread open.

    my $mode = '>>'; # Append my $file_path = '/path/to/file'; my $filehandle; open ( $filehandle, $mode, $file_path ) or die "Unable to open $file_path: $!\n"; print $filehandle "Stuff\n";


    TGI says moo

Re: Changing directories
by Anonymous Monk on May 07, 2008 at 17:53 UTC
    Sory I explained that very poorly; I want $file to be output / saved to the directory 'Pandoras Box' which is within then same directory as the perl script.