简体   繁体   中英

awk array - ghost entries after comparison

I have a simple code snippet consisting of two arrays, and a if comparison

// {
    # 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. 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:

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

To determine whether an element exists in an array at a certain index, use the following expression:

indx in array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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