zsh - 复制数组 1 :1 in zsh

虽然看起来相当简单,但明显的解决方案有细微差别。

以下代码将涵盖大多数情况:

arr_1=(1 2 3 4)
arr_2=($arr_1)

但是,空字符串不会复制。以下代码:

arr_1=('' '' 3 4)
arr_2=($arr_1)
print -l \
  "Array 1 size: $#arr_1" \
  "Array 2 size: $#arr_2"

将产生:

Array 1 size: 4
Array 2 size: 2

我将如何获取数组的真实副本?

最佳答案

这将是一个“Array Subscripts”问题,因此您可以正确指定数组下标形式以选择双引号内数组的所有元素(例如 $arr_1):

arr_1=('' '' 3 4)
arr_2=("${arr_1[@]}")
#=> arr_2=("" "" "3" "4")

$arr_1 的每个元素即使是空的也会被正确地用双引号括起来。

A subscript of the form ‘[*]’ or ‘[@]’ evaluates to all elements of an array; there is no difference between the two except when they appear within double quotes.
‘"$foo[*]"’ evaluates to ‘"$foo[1] $foo[2] ..."’, whereas ‘"$foo[@]"’ evaluates to ‘"$foo[1]" "$foo[2]" ...’.
...
When an array parameter is referenced as ‘$name’ (with no subscript) it evaluates to ‘$name[*]’,

-- Array Subscripts, zshparam(1)

而数组中的空元素会根据“Empty argument removal”去掉,所以

arr_2=($arr_1)
#=> arr_2=(${arr_1[*]})
#=> arr_2=(3 4)

在这种情况下,上述行为并不好。

24. Empty argument removal
If the substitution does not appear in double quotes, any resulting zero-length argument, whether from a scalar or an element of an array, is elided from the list of arguments inserted into the command line.

-- Empty argument removal, Rules Expansion zshexpn(1)

https://stackoverflow.com/questions/35838392/

相关文章:

neural-network - 如何一起使用word2vec和RNN?

Git - 删除或编辑别名

c# - 如何处理内存不足异常字符串生成器

intellij-idea - 为什么 IntelliJ 中的 SBT 可以通过 Internet

sql-server - -S 服务器时出现 sqlcmd 错误

api - 在 POST 中将数据安全地发送到 REST API

r - 使用SparkR,如何将字符串列拆分为 'n'多列?

haskell - 为我的编译器实现代数数据类型

shell - 自解压 tar 存档(shell 脚本)

ruby-on-rails - ApplicationController.rb 中如何使用设计方法