You're creating a closure on $i (with your callback), but then you change $i later in the loop. What you need to do is create a closure on something that will stay locally with that individual closure:
for my $index (0..$#parts) {
my $i = $index; # unique per loop iteration
... rest of your loop here ...
}
This causes a unique $i per iteration, and thus will be closed properly with each callback.
| [reply] [d/l] |
| [reply] [d/l] [select] |
Hi, I just want to point out that you are better off designing things with hashes, instead of arrays. The hashes are easier to deal with in loops, and if you ever decide to turn it into a module, your hash is ready to turn into a namespace. Also, you should let the "-textvariables" do the hard work of updating for you. You can keep your %parts hash in a separate file too, and when you load your script, you can load the %parts hash, and another file containing $parts{$part}{'needed'} values, and they will just fill themselves in, because of the -textvariables.
Look at this:
#!/usr/bin/perl
use warnings;
use strict;
use Tk;
require Tk::Pane;
my %parts = (
11111 => { 'total' => 95,
'add' => 0,
'needed' => 2
},
22222 => { 'total' => 100,
'add' => 0,
'needed' => 0
},
33333 => { 'total' => 800,
'add' => 0,
'needed' => 20
},
44444 => { 'total' => 1000,
'add' => 0,
'needed' => 25
},
55555 => { 'total' => 10,
'add' => 0,
'needed' => 2
},
66666 => { 'total' => 95,
'add' => 0,
'needed' => 2
},
77777 => { 'total' => 100,
'add' => 0,
'needed' => 0
},
88888 => { 'total' => 800,
'add' => 0,
'needed' => 20
},
99999 => { 'total' => 1000,
'add' => 0,
'needed' => 25
},
10101 => { 'total' => 10,
'add' => 0,
'needed' => 2
},
);
my $mw = new MainWindow;
my $pane = $mw->Scrolled( 'Pane', -scrollbars => 'e', )
->grid;
#header
for my $part ( keys %parts ){
$pane->Label( -text => ' part ' )->grid( -row => 0, -column => 0 )
+;
$pane->Label( -text => ' total ' )->grid( -row => 0, -column => 1 )
+;
$pane->Label( -text => ' needed ' )->grid( -row => 0, -column => 2 )
+;
$pane->Label( -text => ' add ' )->grid( -row => 0, -column => 3 )
+;
}
my $row = 0;
for my $part ( sort keys %parts )
{
$row++;
$pane->Label( -text => $part )->grid( -row => $row, -column => 0 );
$pane->Label( -textvariable => \$parts{$part}{'total'} )
->grid( -row => $row, -column => 1 );
$pane->Label( -textvariable => \$parts{$part}{'needed'} )
->grid( -row => $row, -column => 2 );
$parts{$part}{'entry'} =
$pane->Entry( -textvariable => \$parts{$part}{'add'} )
->grid( -row => $row, -column => 3 );
$parts{$part}{'entry'}->bind ("<Return>",
sub { process_add( $part ) });
}
MainLoop;
sub process_add {
my $part = shift;
$parts{$part}{'total'} += $parts{$part}{'add'};
$parts{$part}{'needed'} -= $parts{$part}{'add'};
$parts{$part}{'add'} = 0;
}
I'm not really a human, but I play one on earth.
flash japh
| [reply] [d/l] |