awk - 为什么在 Awk 中未定义用于连接的表达式的求值顺序?

标签 awk

在 GNU Awk 用户指南中,我浏览了 6.2.2 String Concatenation 部分并发现了有趣的见解:

Because string concatenation does not have an explicit operator, it is often necessary to ensure that it happens at the right time by using parentheses to enclose the items to concatenate.


然后,我很惊讶地阅读以下内容:

Parentheses should be used around concatenation in all but the most common contexts, such as on the righthand side of ‘=’. Be careful about the kinds of expressions used in string concatenation. In particular, the order of evaluation of expressions used for concatenation is undefined in the awk language. Consider this example:

BEGIN {
   a = "don't"
   print (a " " (a = "panic"))
}

It is not defined whether the second assignment to a happens before or after the value of a is retrieved for producing the concatenated value. The result could be either ‘don't panic’, or ‘panic panic’.


特别是,在我的 GNU Awk 5.0.0 中,它是这样执行的,在打印值之前进行替换:
$ gawk 'BEGIN {a = "dont"; print (a " " (a = "panic"))}'
dont panic
但是,我想知道:为什么没有定义表达式的求值顺序?根据您运行的 Awk 版本的不同,拥有“未定义”的输出有什么好处?

最佳答案

这个特殊的例子是关于带有副作用的表达式。传统上,在 C 和 awk 语法中(受 C 的启发很大),表达式中允许赋值。然后如何评估这些表达式取决于实现。
保留未指定的内容将确保人们不会使用潜在的混淆或模棱两可的语言结构。但这假设他们知道缺乏规范。

关于awk - 为什么在 Awk 中未定义用于连接的表达式的求值顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65629057/

相关文章:

bash - mysqldump 与 db 在一个单独的文件中

perl - 如果第二个字段长于 7 个字符,则 awk 或 perl 单行打印行

linux - 将 Bash 变量传递给 awk 脚本

linux - 意外的 token 错误 :awk when ran with sh var

hadoop - 从AWS s3提取文件样本并将其放置在s3中的另一个位置

linux - 将与模式匹配的行从一个文件移动到另一个文件

linux - awk脚本中的命令行输入?

linux - 在 bash 脚本中用多行文本替换模式

linux - 用于比较两个大型 900 x 900 逗号分隔文件的脚本

regex - 如何使用动态列对日志输出进行 grep