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

I have list of strings and IDs associated with them, like:
$fruits = {553 => 'apple', 16 => 'orange', 25 => 'lemon', 552 => 'appl +e' }; # and a listbox, displaying them $lb->insert('end', 'apple', 'orange', 'lemon', 'apple');
I'm looking for effective way to store ID and a string together, something like $lb->insert('end', 'apple:553', 'apple:552'); but without displaying the colon and number

so is there a way to assign some custom properties to listbox item?

Replies are listed 'Best First'.
Re: effective way to bind Tk::Listbox items and custom objects
by keszler (Priest) on Jan 07, 2010 at 15:08 UTC
    If you're not married to using a listbox (e.g. more interested in selection than display), Tk::JComboBox and Tk::JBrowseEntry use name:value pairs.
Re: effective way to bind Tk::Listbox items and custom objects
by zentara (Cardinal) on Jan 07, 2010 at 19:26 UTC
    Tk::HList allows some custom properties, but for a simple list, just store the extra data in a hash. Also, Tk objects let you add hash data to an object, as long as you don't interfere with existing methods.

    Like: $lb->'my_extra_data' = my $hash; Then dereference the extra data out when you need it, with out actually listing it

    Here is an example with just a normal hash to store the data

    #!/usr/bin/perl use warnings; use strict; use Tk; my $mw = MainWindow->new; $mw->title("Listbox"); my %grades = ( student1 => { sub1 => 10, sub2 => 20, }, student2 => { sub1 => 30, sub2 => 40, }, student3 => { sub1 => 20, sub2 => 60, }, student4 => { sub1 => 50, sub2 => 50, }, student5 => { sub1 => 90, sub2 => 100, }, ); print "Student Sub1 Sub2\n", '-' x 22, "\n"; for ( sort { $grades{$b}{sub1} <=> $grades{$a}{sub1} } keys %grades ) +{ printf "%-10s%6d%6d\n", $_, $grades{$_}{sub1}, $grades{$_}{sub2}; } #Create the text box and insert the list of choices in to it my $lb = $mw->Scrolled("Listbox", -scrollbars => "osoe", -height => 10, -selectmode => "extended") ->pack(-side => "left"); foreach (sort keys %grades){ $lb->insert("end", $_ ); } $mw->Button(-text => "Exit", -command => sub{exit; })->pack(-side => "bottom"); $mw->Button(-text=>"View", -command => sub { foreach ($lb->curselection()) { my $selected_text = $lb->get($_); print $selected_text,"\t",'sub2= ',$grades{$select +ed_text}{'sub2'}, "\n"; } })->pack(-side => "bottom"); #$lb->selectionSet('end'); $lb->see('end'); MainLoop;

    I'm not really a human, but I play one on earth.
    Old Perl Programmer Haiku