hide random home http://www.fmi.uni-passau.de/archive/doc/unix/perl/faq/2.40.html (Einblicke ins Internet, 10/1995)

What's the difference between delete and undef with %tables?

What's the difference between delete and undef with %tables?


    Pictures help...  here's the %ary table:

              keys  values
            +------+------+
            |  a   |  3   |
            |  x   |  7   |
            |  d   |  0   |
            |  e   |  2   |
            +------+------+

    And these conditions hold

            $ary{'a'}                       is true
            $ary{'d'}                       is false
            defined $ary{'d'}               is true
            defined $ary{'a'}               is true
            grep ($_ eq 'a', keys %ary)     is true

    If you now say 

            undef $ary{'a'}

    your table now reads:
            

              keys  values
            +------+------+
            |  a   | undef|
            |  x   |  7   |
            |  d   |  0   |
            |  e   |  2   |
            +------+------+

    and these conditions now hold; changes in caps:

            $ary{'a'}                       is FALSE
            $ary{'d'}                       is false
            defined $ary{'d'}               is true
            defined $ary{'a'}               is FALSE
            grep ($_ eq 'a', keys %ary)     is true

    Notise the last two: you have an undef value, but a defined key!

    Now, consider this:

            delete $ary{'a'}

    your table now reads:

              keys  values
            +------+------+
            |  x   |  7   |
            |  d   |  0   |
            |  e   |  2   |
            +------+------+

    and these conditions now hold; changes in caps:

            $ary{'a'}                       is false
            $ary{'d'}                       is false
            defined $ary{'d'}               is true
            defined $ary{'a'}               is false
            grep ($_ eq 'a', keys %ary)     is FALSE

    See, the whole entry is gone!