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

Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
"Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon

In reply to Re: Quick question about Tk(?) by BrowserUk
in thread Quick question about Tk(?) by pg

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.