Hi tamaguchi,

It's because you're passing a copy of the variable to your rutine subroutine, rather than a reference to it.

Try this instead:

#!/usr/bin/perl -w + use Tk; use strict; + my $mw = MainWindow->new; + my $var=0; + my $button_A = $mw->Button( -text => ' Button A', -command =>[\&rutine, \$var, ]);# $button_A->pack; + my $button_B = $mw->Button( -text => ' ++ ', -command => sub{$var++; print "\$var is $var!\n";}); $button_B->pack; + my $button_C = $mw->Button( -text => ' -- ', -command => sub{$var--; print"\$var is $var!\n";}); $button_C->pack; + MainLoop; + + sub rutine { my ($pvar)=@_; + print "\$pvar => $$pvar\n"; + }

Update:  To elaborate a bit...

When you create the anonymous subroutine -command => sub{$var++;  print "\$var is $var!\n";}); for the "++" button (and the similar one for "--"), you were still in the same lexical scope of the original my $var=0; a few lines above, so it's not modifying the value of "$var" until it's called.

But in your original code, [-command =>[\&rutine, $var, ]); is taking a "snapshot" of the value of "$var" and using that value instead of the current value.

Another way to fix it would be to simply use an anonymous subroutine (and use your original rutine subroutine) which would correctly use the current value of "$var" when invoked:

my $button_A = $mw->Button( -text => ' Button A', # -command =>[\&rutine, \$var, ]);# -command => sub{ rutine($var) }); $button_A->pack; # ... sub rutine { my ($var)=@_; + print "\$var => $var\n"; + }

s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/

In reply to Re: Fundamental tk-problem by liverpole
in thread Fundamental tk-problem by tamaguchi

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.