Search code examples
perldirectory

how to access files from a different directory using perl


I am getting file names using command line arguments to Perl. I know the the file locations. How to change directories to use the corresponding files ? I need to go up the directory tree to get and then go down a different branch to get to those input files.

How to anchor in the top branch and then change directories? I just started learning perl this week. So any help would be great.

proj
    branch1
           file.pl
    branch2
           file_I_WANT_TO_ACCESS

Solution

  • Perl has a chdir() function for changing directory. But you probably don't need that as whatever you're trying to do with the files will almost certainly allow you to use full paths to the files.

    Note that there are three directories that you need to keep clear in your mind:

    • The directory that contains your Perl program (proj/branch1 in your example)
    • The directory where you are when you run the Perl program (that could be the same as the directory that contains the program - but it doesn't have to be)
    • The directory containing the file that you want to read (proj/branch2 in your example)

    The FindBin module (part of the standard Perl library) will be useful here as it will tell you the directory where your program is and you can often work out the rest of the locations from that.

    For example:

    # $RealBin will contain the directory that you program is in
    use FindBin '$RealBin';
    
    # '..' goes up a level to proj
    # Then go down into branch2 to find your file
    my $file = "$RealBin/../branch2/file_I_WANT_TO_ACCESS";
    

    Note that we don't need to call chdir() here at all. We're just using full paths to the files.