cjhutton
cjhutton

Reputation: 91

Build array of the contents of the working directory in perl

I am working on a script which utilizes files in surrounding directories using a path such as

"./dir/file.txt"

This works fine, as long as the working directory is the one containing the script. However the script is going out to multiple users and some people may not change their working directory and run the script by typing its entire path like this:

./path/to/script/my_script.pl

This poses a problem as when the script tries to access ./dir/file.txt it is looking for the /dir directory in the home directory, and of course, it can't fine it.

I am trying to utilize readdir and chdir to correct the directory if it isn't the right one, here is what I have so far:

my $working_directory = $ENV{PWD};
print "Working directory: $working_directory\n";       #accurately prints working directory
my @directory = readdir $working_directory;            #crashes script

if (!("my_script.pl" ~~ @directory)){                  #if my_script.pl isnt in @directoryies, do this
    print "Adjusting directory so I work\n";
    print "Your old directory: $ENV{PWD}\n";
    chdir $ENV{HOME};                                  #make the directory home
    chdir "./path/to/script/my_script.pl";             #make the directory correct
    print "Your new directory: $ENV{PWD}\n";
}

The line containing readdir crashes my script with the following error

Bad symbol for dirhandle at ./path/to/script/my_script.pl line 250.

which I find very strange because I am running this from the home directory which prints out properly right beforehand and contains nothing to do with the "bad symbol"

I'm open to any solutions

Thank you in advance

Upvotes: 0

Views: 114

Answers (2)

Sobrique
Sobrique

Reputation: 53508

I think you're going about this the wrong way. If you're looking for a file that's travelling with your script, then what you probably should consider is the FindBin module - that lets you figure out the path to your script, for use in path links.

So e.g.

use FindBin;
my $script_path = $FindBin::Bin; 

open ( my $input, '<', "$script_path/dir/file.txt" ) or warn $!;

That way you don't have to faff about with chdir and readdir etc.

Upvotes: 1

sidyll
sidyll

Reputation: 59307

The readdir operates with a directory handle, not a path on a string. You need to do something like:

opendir(my $dh, $working_directory) || die "can't opendir: $!";
my @directory = readdir($dh);

Check perldoc for both readdir and opendir.

Upvotes: 1

Related Questions