Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

opening new file in different directory

by George_Sherston (Vicar)
on Oct 23, 2001 at 18:42 UTC ( #120797=perlquestion: print w/replies, xml ) Need Help??

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

Sorry if this is obvious, but it isn't to me alas:

I want to open a file in one directory, read the contents, mess with them, and write them into another file with the same name (call it $file) in a different directory. Relative to where my script is, both of these directories are down one and up two. Now, to read first file I do open (READ, "/home/main/sub/oldfiles/$file") or die "could not open /home/main/sub/oldfiles/$file $!"; That's fine, although it wd be nice if I didn't have to write out the whole file path. I'd like to be able to do open (READ, "../sub/oldfiles/$file") or die "could not open ../sub/oldfiles/$file $!"; But that doesn't work. Perhaps it's not meant to work. Anyhow, the real problem comes when I want to write to a new file:
open (READ, ">/home/main/sub/newfiles/$file") or die "could not open / +home/main/sub/newfiles/$file $!";
d-oesn't work. At the moment what I'm doing is
chdir "/home/main/sub/newfiles"; open (WRITE,">$file") or die "could not open $file $!"; # write stuff chdir "/home/main/cgi-bin";
But that seems clunky. I'd welcome any advice how to do it nicer, and any explanation of why the different things I'd like to do don't work. As you can see I don't really understand the science of directories very well: I long for enlightenment.

George Sherston

Replies are listed 'Best First'.
Re: opening new file in different directory
by graq (Curate) on Oct 23, 2001 at 19:10 UTC
    To start with, I would not use relative paths. I would define a base path and work from there.
    #!perl -w use strict; my $file = "graq.txt"; my $source = &get_path("oldfiles/$file"); my $result = &get_path("newfiles/$file"); open( READ, "<$source" ) or die( "Could not open $source: $!\n" ); open( WRITE, ">$result" ) or die( "Could not write to $result: $!\n" ) +; while(<READ>) { # Do stuff. print WRITE $_; } close WRITE; close READ; # --------------------------------- # Local Functions. sub base_path { '/home/main/sub'; } sub get_path { return &base_path."/".$_[0]; }
    You could define them with use constant or some other way. Which is just another TIMTOWTDI...

    editTypo in die()/edit


      I might be being a bit thick but I can't get it to work. It looks as though the WRITE line only works if $result is a file, not a file path. I find that
      my $file = "/home/htdocs/hosted/thinweb/ +savedsearches/$g{'SearchFile'}"; open(WRITE,">$file") or die $!;
      fails, whereas
      chdir "/home/htdocs/hosted/thinweb/ +searches"; open(WRITE,">$g{'SearchFile'}") or die $!;
      succeeds. (NB the earlier lines I posted were re-written to make the examples easier to read - the above are as in my actual script, just in case there's something else funny going on... in which case I apologise for my over-zealous desire to do a tidy post).

      George Sherston
        Ok. First things first, add some verbosity to your error handling:
        open(WRITE,">$file") or die( "Cannot write to $file: $!" );

        And then let us know what the whole error is, makes it much easier :)


        Man this smells like a permissions issue. It's possible to have permission to cd into a directory without having permission to ls in it. This is a freaky benefit of the *nix user/group permission bits. If'n I was you, I'd play with accessing these files from the command line, just with touch and vi, to see if there's some intermediate directory that's got permission funkiness. Make sure you do this with the user that the script runs as.

        Or, another good thing to see, would be the ls -ld output on the directories you've listed up there.

        This is one of those things that, as blackmateria said, should work. It's irritating that it doesn't.


        "So... What do all these little arrows mean?"

Re: opening new file in different directory
by VSarkiss (Monsignor) on Oct 23, 2001 at 18:53 UTC

    Umm, maybe I'm not following you correctly here, but it looks like you have a bit of a mish-mosh. Relative paths (like those starting with "..") start from your current directory. To do what you're looking for, you need to change your directory first. Something like this should work:

    chdir "/home/main/sub/oldfiles"; # or wherever open READ, "$file" # open READ ">$file" is a typo, no? or die "Couldn't open $file to read: $!\n"; # ... Do stuff, ready to write open WRITE1, "> ../newfiles/$file" or die "Couldn't open $file to write: $!\n"; # ..Whatever... open WRITE2, ">../../cgi-bin/$file" or die "Couldn't open $file to write: $!\n";
    This works fine on an HP-UX box, using 5.005_02.

    Did I answer the right question?


      I think this isn't the answer because I think (which I shd have spelled out) the current directory is /home/main/cgi-bin. The reason I'm a bit equivocal is that I do not explicitly set it to be the current directory; it's jus the directory where my script resides. Is that the problem? Why?

      George Sherston

        Two things: First, depending on the server configuration, the script may or may not be executing in the directory in which the file is installed. It's not where the script is installed that matters, but the current directory of the Perl process that's executing your script.

        Second, more importantly: if you depend on a particular path, don't assume you're starting there, chdir to that directory explicitly. It guarantees your paths and has negligible overhead. If you're worried about spelling out the directory name in your script, read it in from the environment or some such. But don't assume your script will always execute in the same place.

Re: opening new file in different directory
by nardo (Friar) on Oct 23, 2001 at 18:54 UTC
    If the last block of code is copied exactly then you are opening WRITE for reading which doesn't sound like what you want to do. If that works, but opening it for writing doesn't then you probably don't have permission to write to the file, but without telling us the value of $! it's difficult to diagnose exactly what your problems are.
      Huh, quite right, my bad. I've amended my WRITE (actually... it's a root node... but the excellent davorg obliged). The error message I get when opening the file for writing is No such file or directory

      George Sherston
Re: opening new file in different directory
by buckaduck (Chaplain) on Oct 24, 2001 at 00:55 UTC
    How about one more layer of error checking, on the chdir command:
    chdir "/home/main/sub/newfiles" or die $!; open(WRITE, ">$file") or die "Can't open $file: $!";
    That is, just because the program runs, doesn't mean it's working correctly. It's possible that the chdir fails and the open is creating a file in the current directory. It's worth checking, anyway...


Re: opening new file in different directory
by blackmateria (Chaplain) on Oct 23, 2001 at 18:50 UTC
    That's strange. I would think it was some funky thing with not having w or x permission for one of the directories in the pathname, except then the chdir trick wouldn't work (I don't think). What errors are you getting (in $!)?
Re: opening new file in different directory
by Anonymous Monk on Aug 01, 2013 at 11:26 UTC

    Use double back slash inside the path

     open (FH,"C:\\Dirname\\filename.txt")

    This will work

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://120797]
Approved by root
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2022-07-02 17:49 GMT
Find Nodes?
    Voting Booth?
    My most frequent journeys are powered by:

    Results (103 votes). Check out past polls.