in reply to Re^3: Perl Tk label references
in thread Perl Tk label references

++ Good job improving that part on your own...

Now look at what your original button's sub does: it assigned a new, empty hashref to the $ref_hash variable (as AM pointed out by printing multiple addresses when assigning the variable to multiple empty hashrefs: {}). Your updated one is an improvement, because it's accessing the original memory, rather than creating a new memory space. But you're deleting the keys and their values, rather than keeping the keys and just clearing the values.

update: strike out something that might not be accurate. But your second code was still an improvement, because you learned you needed to de-reference the hashref, rather than assigning a new empty hashref {}

Replies are listed 'Best First'.
Re^5: Perl Tk label references
by pryrt (Abbot) on Nov 10, 2016 at 22:20 UTC

    BTW: many monks will recommend use warnings; use strict;: this would have shown your original \$ref_hash{'VM-1'} issue at compile-time.

    edit: ... and many consider a more readable de-referencing for a hashref to be \$ref_hash->{'VM-1'} instead of \$$ref_hash{'VM-1'} (I knew I wanted to say two things, but when I replied to myself, I couldn't recall the second.)

      Thanks for the reply. In the production code I do use strict & warnings. Should have in the test program too. Oops. AH! Excellent! I am clearing the whole hash. Duh! Thanks so much. And thanks for the tip. Big thanks!! ;-) For completeness, the new code works.

      use Tk; use strict; use warnings; require Tk::Entry; require Tk::Button; my $mw = MainWindow->new(); my %work = ( "VM-1" => "da923", "VM-2" => "dz427"); main_display(\%work); MainLoop; # ----------------------------------------------------- sub main_display { my $ref_hash = shift(@_); my $lab1 = $mw->Label(-textvariable => \$ref_hash->{'VM-1'}, -relief => 'sunken', -width => 10, )->pack(); my $lab2 = $mw->Label(-textvariable => \$ref_hash->{'VM-2'}, -relief => 'sunken', -width => 10, )->pack(); my $but = $mw->Button(-text=>'clear', -command=> [sub{ $ref_hash->{'VM-1'} = " "; $ref_hash->{'VM-2'} = " "; $mw -> update; }] )->pack(); }