简体   繁体   English

awk数组-比较后的幻像条目

[英]awk array - ghost entries after comparison

I have a simple code snippet consisting of two arrays, and a if comparison 我有一个包含两个数组的简单代码段,以及一个if比较

// {
    # Create an array
    animals["goat"] = "4 legs"
    animals["chicken"] = "2 legs"
    animals["elefant"] = "4 legs"

    for (animal in animals) {
        print "Animal: " animal " has: " animals[animal]
    }


    zoo["lion"] = "4 legs"
    zoo["leguana"] = "4 legs"

    for (animal in zoo) {
        if (animals[animal] != "2 legs") {
            # do something
        }
    }

    for (animal in animals) {
        print "Again. Animal: " animal " has: " animals[animal]
    }

}

The input file doesnt matter. 输入文件无关紧要。

So the problem lies in the for loop with the if statement within. 因此问题出在带有if语句的for循环中。 I would expect it to simply compare if different values in the array "animals" is not equals to "2 legs" but what is happening is this: 我希望它可以简单地比较数组“ animals”中的不同值是否不等于“ 2条腿”,但这是怎么回事:

Animal: chicken has: 2 legs
Animal: goat has: 4 legs
Animal: elefant has: 4 legs
Again. Animal: chicken has: 2 legs
Again. Animal: goat has: 4 legs
Again. Animal: elefant has: 4 legs
Again. Animal: lion has:
Again. Animal: leguana has:

Notice that suddenly the array "animals" has two new keys, lion an leguana, however without value. 请注意,数组“动物”突然有了两个新键,即狮身像,但没有价值。 Why is this happening? 为什么会这样呢? the =! =! should not assign a value, it should merely see if there is a value for a key, a key that might not exist in the array. 不应分配值,而应仅查看键是否存在值,该键可能在数组中不存在。 Is there a way to check if a key that might not exist in the array has a certain value withouh creating the key in the array? 是否可以通过在数组中创建键来检查数组中可能不存在的键是否具有特定值?

You have to protect, the instruction, animals[animal] with animal in animals 您必须保护动物说明书中的动物[动物]

for (animal in zoo) {
  if (animal in animals && animals[animal] != "2 legs") {
         print "Then Animal:" animal 
  }
  else {
         print "Else Animal:" animal
  }
}

Eventually I found the answer here: https://www.gnu.org/software/gawk/manual/html_node/Reference-to-Elements.html 最终我在这里找到了答案: https//www.gnu.org/software/gawk/manual/html_node/Reference-to-Elements.html

To determine whether an element exists in an array at a certain index, use the following expression: 要确定某个元素在数组中是否存在某个索引,请使用以下表达式:

indx in array 数组中的indx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM