in reply to -textvariable won't update when using hash element

The problem is that the -textvariable parameter is taking a reference to the value in the hash - you know that of course, but there is a trap. When you assign the new hash to the old hash you are replacing the contents of the old hash, both keys and values, and most likely the values end up stored in a different place so the original reference isn't doing you any good any more. As an illustration of what's going on consider:

#!/usr/bin/env perl use warnings; use strict; my %fnr = ( COMPANY_CODE => 'AB', COMPANY_NAME => 'ABC, Inc.', ); my %fnr_loop = ( COMPANY_CODE => 'XY', COMPANY_NAME => 'XYZ, Inc.', ); my %fnr_but = ( COMPANY_CODE => 'PQ', COMPANY_NAME => 'PQR, Inc.', ); my $nameRef = \$fnr{COMPANY_CODE}; show('Original'); changeHashLoop(); show('Loop'); changeHashButton(); show('Button'); sub changeHashButton { %fnr = %fnr_but; } sub changeHashLoop { for my $key (keys %fnr) { $fnr{$key} = $fnr_loop{$key}; } } sub show { my ($label) = @_; my $ccRef = \$fnr{COMPANY_CODE}; printf "%8s: %s (%s) FNR: %s (%s)\n", $label, $$nameRef, $nameRef, $$ccRef, $ccRef; }

Prints:

Original: AB (SCALAR(0x94a554)) FNR: AB (SCALAR(0x94a554)) Loop: XY (SCALAR(0x94a554)) FNR: XY (SCALAR(0x94a554)) Button: XY (SCALAR(0x94a554)) FNR: PQ (SCALAR(0x94a584))

Note the change in the address of the FNR value when the hash copy has been made.

True laziness is hard work

Replies are listed 'Best First'.
Re^2: -textvariable won't update when using hash element
by LivingDust (Novice) on May 09, 2013 at 15:37 UTC

    Thanks! That makes perfect sense. So what is happening is the reference address stored in:

    -textvariable => \$fnr{COMPANY_CODE},

    still exists but has been abandoned after

         %fnr = %fnr_new;

    No change is detected because what was stored at that address didn't change and will never change (unless the abandoned address got recycled.) Correct?

    There are only 10 types of people in this world... those who understand binary, and those who don't.
      "So what is happening is ..."

      Yep, got it in one. I'm sure I've been bitten by this in the dim distant past, and spent considerable time trying to figure out where the bug in Tk was!

      True laziness is hard work