smackdab has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,
In a sub, when I do: my $rs_en1 = shift(); I can set the value of en1: $$rs_en1 = "new" But, if I do: my $en1 = ${shift()}; Setting $en1 = "new" doesn't work
(I am setting some values in a Tk::Entry widget... and I wonder why both are not equiv...)
thanks

Replies are listed 'Best First'.
Re: deref question
by graff (Chancellor) on Apr 10, 2003 at 03:33 UTC
    The two are not equivalent. Given that the item being shifted is a reference to a scalar, the first case makes a copy of the reference, in the sense that "$rs_en1" is also a reference to the same scalar -- i.e. it points to the same location in memory, and using it as a reference affects that location.

    Meanwhile, the second case de-references the item being shifted, and so assigns the value of the scalar to $en1 -- as a result, $en1 contains a copy of the value and this copy has its own distinct location in memory, separate from the location pointed to by the reference that was shifted.

Re: deref question
by pg (Canon) on Apr 10, 2003 at 05:57 UTC
    Not sure how you used Tk::Entry. If you use the textvariable option of Tk::Entry, it becomes much more simple for you to set/get the content of Tk::Entry (avoid passing params to your callback function, and do all those handling by yourself, that is more complex):
    use Tk; use strict; my $entry_val = "initial value"; my $mw = new MainWindow(title => "demo"); $mw->Entry(width => 20, textvariable => \$entry_val)->pack; $mw->Button(text => "click", command => sub {print $entry_val, "\n";}) +->pack; MainLoop;