in reply to Quick question about Tk(?)
As JediWizard identified, using $_ as your id is the source of the problem, though his solutions aren't quite right.
In his first example, quoting $_ won't do the trick, and in the second the quoting is unnecessary.
You could also use your current code (with corrections:), but name the loop iterator. By naming the iterator, the sub will form a closure over the lexical and achieve the results you want.
#! perl -slw use strict; use Tk; use Data::Dumper; use XML::Simple; use strict; use warnings; my $tasks = XMLin(<<EOS); <tasks> <task description="task1"></task> <task description="task2"></task> <task description="task3"></task> <task description="task4"></task> <task description="task5"></task> <task description="task6"></task> </tasks> EOS print Dumper($tasks); my $mw = MainWindow->new(); ## What was $#{@{$tasks->{"task"}}} all about :) for my $id ( 0 .. $#{ $tasks->{task} } ) { $mw->Button( -text => $tasks->{task}[$id]{description}, -command => sub { pub( $id ) } )->pack(); } MainLoop; sub pub { my $task_id = shift; print "task id = $task_id"; } __END__ P:\test>junk $VAR1 = { 'task' => [ { 'description' => 'task1' }, { 'description' => 'task2' }, { 'description' => 'task3' }, { 'description' => 'task4' }, { 'description' => 'task5' }, { 'description' => 'task6' } ] }; task id = 0 task id = 1 task id = 2 task id = 3 task id = 4 task id = 5
|
|---|