为什么花括号不能被Perl中的周围反引号解释?

时间:2014-02-08 11:11:06

标签: perl bash

my @cmd=`ls {??_in,??}.pl`;
print @cmd;

如果运行该程序则说错误

    `ls: cannot access {??_in,??}.pl: No such file or directory`

现在已经在终端上运行了

cmd>ls {??,??_in}.pl

cmd>aa_in.pl aa.pl ls.pl

所以它的产生输出在commad行中,为什么perl不考虑大括号。

2 个答案:

答案 0 :(得分:7)

您可以使用Perl's glob built-in获取该文件列表,而不是对ls进行系统调用。

use Data::Dump;
dd [ glob '{??_in,??}.pl' ];

将打印与模式匹配的文件列表。 glob将负责填写通配符并查找文件。


另请注意,您要将反引号的返回值指定给标量变量$cmd,但您正在尝试打印数组@cmd。这些是不同的变量。它还会导致错误全局符号“@cmd”需要显式包名... 如果您已启用use strict(您应该这样做!)。

答案 1 :(得分:6)

我认为这是基于调用哪个shell。您正在使用特定于bash的大括号扩展,POSIX shell不支持。

在我的系统上,我得到了这些结果:

$ perl -e '`sh -c "ls src/{*.pl,*.h}"` and print "success\n"'
ls: cannot access src/{*.pl,*.h}: No such file or directory

$ perl -e '`bash -c "ls src/{*.pl,*.h}"` and print "success\n"'
success

所以,我的结论是perl叫'sh'。你可以像我的例子一样使用“bash -c”来解决它。