in reply to Re: Creating variables for each array member
in thread Creating variables for each array member
In general where you want to cart some context around stuffing disperate objects into a hash is excellent. In the case OP has stated an array is the natural structure.
Your sample reworked to use an array and to fix the "doesn't print the actual button text" issue becomes:
#!/usr/bin/perl use warnings; use Tk; my $mw = tkinit; my @buttons; for $i ( 0..5 ) { $buttons[$i] = $mw->Button(-text => "Button $i",)->pack(); $buttons[$i]->configure (-command => [\&printme, $buttons[$i]],); } my $reconbut = $mw->Button(-text => 'Reconfigure', -command => \&recon +,)->pack(); MainLoop; sub printme { print $_[0]->cget (-text) . "\n"; } sub recon{ $buttons[$_]->configure(-text => 'Button '. ($_ + 10)) for 0..$#bu +ttons; }
OP should note that an important difference between using the hash and an array is that the hash doesn't preserve insertion order (unless you use a little magic) which is why zentara's code used foreach my $key (sort keys %buttonhash) to iterate over the buttons (although the sort isn't actually required in this case) where the array version uses for 0..$#buttons.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Creating variables for each array member
by zentara (Cardinal) on Jul 26, 2006 at 12:29 UTC |