我在awk
. 我想删除一个数组元素,但发现这个元素(只是一个索引,没有值)再次出现,如果我在删除后在代码中的某个地方使用它。这是预期的行为吗?
awk '
# This function just for clarity and convenience.
function check(item) {
if(item in arr)
printf "the array index \"%s\" exists\n\n", item
else
printf "the array index \"%s\" does not exist\n\n", item
}
END {
# Create element of array with index "f"
arr["f"] = "yes"
printf "The value of arr[\"f\"] before deleting = \"%s\"\n", arr["f"]
# The first checking of the array - the index exists
check("f")
# Then delete this element
# I am expecting no this element in the "arr" now
delete arr["f"]
# The second checking of the array - the index does not exist
# as I were expecting
check("f")
# Use the non-existent index in expression
printf "The value of arr[\"f\"] after deleting = \"%s\"\n", arr["f"]
# The third checking of the array - the index exists again
check("f")
}' input.txt
输出
The value of arr["f"] before deleting = "yes"
the array index "f" exists
the array index "f" does not exist
The value of arr["f"] after deleting = ""
the array index "f" exists
您遇到的行为是因为此行以静默方式重新创建您之前删除的数组项:
看这个小测试:
这是预期的行为。如果变量尚不存在,则引用变量的值将创建它。否则,以下将是语法错误:
即使对于非数组变量也是如此,但由于
delete
平面变量没有运算符(有时),因此如果问题不涉及数组,这不会经常出现。