bug-gawk
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [bug-gawk] Can a key in a array be deleted while the array is iterat


From: Manuel Collado
Subject: Re: [bug-gawk] Can a key in a array be deleted while the array is iterated?
Date: Tue, 03 Jan 2017 15:56:16 +0100
User-agent: Mozilla/5.0 (Windows NT 5.1; rv:17.0) Gecko/17.0 Thunderbird/17.0

El 02/01/2017 4:19, Andrew J. Schorr escribió:

On Sun, Jan 01, 2017 at 07:05:29PM -0600, Peng Yu wrote:
I made the following function to intersect the keys of x1 and x2. The
results is saved in x1. I am not sure it is OK to change an array
while it is being iterated. Will the function always work? Thanks.

function arrkeyintersect(x1, x2,    k) {
     for(k in x1) {
         if(!(k in x2)) {
             delete x1[k]
         }
     }
}

It is safe. This should be apparent from the documentation:
    https://www.gnu.org/software/gawk/manual/html_node/Delete.html

Well, it seems safe to modify the current iterated array element. But modifying array elements other then the current one may be troublesome.

In this particular case, the original code could be modified by iterating over the second (unchanged) array instead of the first (been modified) one. As follows:

function arrkeyintersect(x1, x2,    k) {
    for(k in x2) {
        delete x1[k]
        }
    }
}

HTH.
--
Manuel Collado - http://lml.ls.fi.upm.es/~mcollado




reply via email to

[Prev in Thread] Current Thread [Next in Thread]