0

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?

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
Paul IT
  • 85
  • 5
  • 1
    How do you know it's not? What do you expect to happen? – simbabque Aug 11 '20 at 15:55
  • I don't see any error checking in that. Are you using the `autodie` pragma? How do you know it's not working? – Shawn Aug 11 '20 at 16:00
  • 1
    The complete commands are as below: chdir "/home/test/test1/test2/perl*"; exec "cat test.in | grep build | awk '{print \$2}'"; After executing the script, it is showing the error: cat: test.in: No such file or directory – Paul IT Aug 11 '20 at 16:02
  • 2
    You should put that in your question, not a comment. – Shawn Aug 11 '20 at 16:15

3 Answers3

5

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: $!";
}
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
4

chdir expects a path, not a wildcard. Use glob to expand the wildcard:

my ($dir) = glob "/home/test/test1/test2/perl*";
chdir $dir or die "$dir: $!";

If there are multiple expansions, the first one will be used.

choroba
  • 231,213
  • 25
  • 204
  • 289
0

In similar vein, glob is handled by a module in raku https://modules.raku.org/dist/IO::Glob

librasteve
  • 6,832
  • 8
  • 30