perldirectoryglobchdir

Perl chdir fails with a glob pattern


I am trying to do cd in my perl script. I am using the below command:

chdir "/home/test/test1/test2/perl*";

perl* value is actually perl_0122_2044, but this value may vary.

The above chdir command is not doing cd to the path. Am I doing something wrong?


Solution

  • chdir does not accept * and other expansion characters in the argument. Use glob or something similar for this to extract a single directory, then chdir to that. For example, this changes directory to the first /home/test/test1/test2/perl* it finds:

    $dir = (glob "/home/test/test1/test2/perl*")[0];
    # only change dir if any dir was found: 
    if (-d $dir) {
        # fail if cannot change dir (or, even better, use autodie):
        chdir $dir or die "Could not change to $dir: $!";
    }