Welcome, guest | Sign In | My Account | Store | Cart

Comparing two arrays for differences.

Tcl, 33 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#
# cmpArray { a1 a2 }
#
# returns <list of indexes where there are differences>
#

proc cmpArray { ary1 ary2 } {
    upvar $ary1 a1
    upvar $ary2 a2

    set ilist1 [array names a1]
    set ilist2 [array names a2]

    foreach idx $ilist1 {
        # Make sure ary2 HAS this element!
        if {![info exists a2($idx)]} {
            # We don't have this element so...
            continue
        }

        if {$a1($idx) != $a2($idx)} {
            # They are not the same!
            lappend retn_list $idx
        }
    }

    if {![info exists retn_list]} {
        # There ARE no differences so return an empty list
        set retn_list [list {}]
    }

    return $retn_list
}

Comparing two similar arrays can be very handy for form entry (saving only changes or detecting if there ARE any changes). This reciepe provides a simple compare function that takes two array NAMES as input and returns a list of the indexes where there are differences. If the arrays are the same, an empty list is returned.

Note that this will only compare array elements that have the same index. "Extra" or "missing" indexes will not be compared (or noted in any way for that matter).

I find this most useful in data entry applications where I want either an "undo" function (at the time the record is read, create a "mirrored" array of the values to be used if "undo" is selected) and also for saving just the CHANGES to a record. You could also use it to validate only the items that have been changed instead of every entry in the form.

Created by Len Morgan on Wed, 5 Feb 2003 (MIT)
Tcl recipes (162)
Len Morgan's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks