【问题标题】:Perl chdir fails with a glob patternPerl chdir 以 glob 模式失败
【发布时间】:2020-08-11 15:52:40
【问题描述】:

我正在尝试在我的 perl 脚本中执行 cd。我正在使用以下命令:

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

perl* 的值实际上是perl_0122_2044,但这个值可能会有所不同。

上面的chdir 命令没有对路径执行cd。我是不是做错了什么?

【问题讨论】:

  • 你怎么知道不是?你预计会发生什么?
  • 我没有看到任何错误检查。你在使用autodie 编译指示吗?你怎么知道它不起作用?
  • 完整的命令如下: chdir "/home/test/test1/test2/perl*"; exec "cat test.in | grep build | awk '{print \$2}'";执行脚本后,报错:cat: test.in: No such file or directory
  • 你应该把它放在你的问题中,而不是评论中。

标签: perl directory glob chdir


【解决方案1】:

chdir 不接受 * 和参数中的其他扩展字符。使用glob 或类似的东西来提取一个single 目录,然后chdir 到那个目录。例如,这会将目录更改为它找到的第一个 /home/test/test1/test2/perl*

$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: $!";
}

【讨论】:

  • 并检查该错误,主要是查看它尝试过的目录:chdir $dir or die "Could not change to $dir: $!";
  • @briandfoy 感谢您的提醒,添加了这个和一个额外的检查!
【解决方案2】:

chdir 需要一个路径,而不是通配符。使用glob 扩展通配符:

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

如果有多个扩展,将使用第一个。

【讨论】:

    【解决方案3】:

    类似地,glob 由 raku https://modules.raku.org/dist/IO::Glob 中的模块处理

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多