Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
Greetings, O wise ones.
I am working on a Tk interface for my very first Useful Program[1]. The main window contains several frames which contain very similar widgets. I want to be able to pack/packForget the frames dynamically, so to improve readibility I would like each frame to have a descriptive name. I.e. not the frames should be elements of an array or something similar.
On the other hand, since the widgets inside each frame are so similar, I thought it would make sense to pack the widgets in a loop, packing one frame per cycle. I basically have a list of elements I wanted to iterate over, so a foreach loop seemed ideal. My first (and so far only) idea was to do something like this:
use strict; use Tk; my $mw = MainWindow->new; my $hello_string = "Hello"; my $silly_string = "Very Silly!!!"; my $frame1 = $mw->Frame(); my $frame2 = $mw->Frame(); my $frame3 = $mw->Frame(); my $frame4 = $mw->Frame(); my %frame_var_hash = ($frame1 => {-text => $hello_string, width => 7}, $frame2 => {-text => $silly_string, width => 9}, $frame3 => {-text => "XXXXX", width => 35}, $frame4 => {-text => $silly_string, width => 7}); foreach my $cur_frame (keys %frame_var_hash){ $cur_frame->Label( $frame_var_hash{$cur_frame}, -expand => 1, )->pack(); } [...] MainLoop;
I thought this was fairly clever (I impress myself easily) but Perl disagreed:
Can't locate object method label via package "Tk::Frme=HASH(0x286D960)" (perhaps you forgot to load "Tk::Frme=HASH(0x286D960)"? at test line 27.
My reading of the camel book suggests that the loop variable takes on the identity of whatever list element is assigned to it. For example,
foreach $element (@some_array){$element++}
actually increments the values in $some_array. Apparently this doesn't hold in a straightforward way for objects. I tried de-referencing $cur_frame, I tried using references to the frame objects as the keys in %frame_var_hash and then de-referencing $cur_frame, and I think I tried some other things but it was late and I forget.
Is there a way to make a loop like this work? Is there a better way to solve the problem? I am seated at you feet, listening.
-- Fuzzy Frog
[1] The guts have been working for almost two years. I just want to give it a pretty face. The person who will be taking over my job has never heard of a command line.Edited by Chady -- escaped barackets and made them into a nice footnote link.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Iterating over objects
by japhy (Canon) on May 18, 2004 at 23:03 UTC | |
by Fuzzy Frog (Sexton) on May 19, 2004 at 03:10 UTC | |
|
Re: Iterating over objects
by BUU (Prior) on May 18, 2004 at 22:12 UTC | |
|
Re: Iterating over objects
by dimar (Curate) on May 18, 2004 at 22:58 UTC | |
|
Re: Iterating over objects
by Fuzzy Frog (Sexton) on May 18, 2004 at 21:55 UTC |