windows - perl 优先于 glob @argv

标签 windows perl glob operator-precedence

因为在 Windows 上 *.csv 不会从命令行扩展到 @ARGV 我通常最终会做类似的事情

map { glob } @ARGV 获取文件名。

然而,我遇到了一个异常,只是想了解到底发生了什么。我刚刚读完《异地奇缘》,所以我可以说我没有完全理解!

use Modern::Perl;

# gets the filelist but then warns
say "Test 1 ", '-' x 20;
do { func($_) for map { glob } @ARGV } or warn "at least one arg expected\n";
say '-' x 27, "\n";

# works ok
say "Test 2 ", '-' x 20;
my @x = map { glob } @ARGV or warn "at least one arg expected\n";
func($_) for @x;
say '-' x 27, "\n";

# prints 2 (there are two files)
say "Test 3 ", '-' x 20;
func($_) for (map { glob } @ARGV or warn "at least one arg expected\n");
say '-' x 27, "\n";

sub func { 
  say "in func = $_[0]";
}

输出:

Test 1 --------------------
in func = t.csv
in func = t2.csv
at least one arg expected
---------------------------

Test 2 --------------------
in func = t.csv
in func = t2.csv
---------------------------

Test 3 --------------------
in func = 2
---------------------------

测试 1: 我不明白为什么 do 没有真正返回,func 返回最后一个语句是 say,如果有输出则返回 true。还是 for 用作 do 的返回值?

测试 3: 显然标量上下文是隐含的,但如何呢?我在 map 周围使用了括号?

谢谢, 理查德。

最佳答案

测试 1

第一种情况是由于 for 语句修饰符而评估为 false(您可能认为它是无效的)。观察:

  DB<1> x do { func($_) for map { glob } @ARGV }
in func = t.csv
in func = t2.csv
0  ''
  DB<2> x do { func 't.csv' ; func 't2.csv' }
in func = t.csv
in func = t2.csv
0  1

请注意,它是一个语句修饰符,而不是表达式修饰符。在做出这种区分的语言中,表达式有返回值但没有语句。

Perl 就是这样一种语言。给出简单的程序

#! perl
@a = (1 for 6, 7, 8);

尝试运行它失败并出现语法错误。

syntax error at foo line 2, near "1 for "
Execution of foo aborted due to compilation errors.

You might express your intent in the first test more directly

map func($_), map glob, @ARGV or warn "at least one arg expected\n";

给出预期的输出。

Test 1 --------------------
in func = t.csv
in func = t2.csv
---------------------------

测试 3

在第三种情况下,您获得标量上下文,因为这就是 Perl’s logical-or 的方式被定义为工作。

C-style Logical Or

Binary || performs a short-circuit logical OR operation. That is, if the left operand is true, the right operand is not even evaluated. Scalar or list context propagates down to the right operand if it is evaluated.

左操作数始终在二进制(标量)上下文中求值。整个表达式的上下文仅归因于右操作数。

关于windows - perl 优先于 glob @argv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10932327/

相关文章:

windows - ansi 终端和 native io 管理器不起作用

perl - 在 perl 中使用 stat 时 $mode 保存什么

python - 仅使用一次 glob 搜索多个模式

python - ValueError : could not convert string to float: 'samples.txt'

windows - 如何更改/查看 Windows 机器上的临时端口范围?

windows - Git 在 Windows 中工作吗?

python - 如何有效地分配预定义大小的文件并使用 Python 将其填充为非零值?

linux - 我的 Perl 模块已找到但未被应用

mysql - Perl:将 $dbh 交给模块。安全性和性能?

bash - 在 bashrc 中为 GREP_OPTIONS 匹配文件类型 --exclude