in reply to Creating variables for each array member

Learn to stuff your objects into hashes. Once you get the idea, it makes looping thru them a breeze. Here is a simple example.
#!/usr/bin/perl use warnings; use Tk; my $mw = tkinit; my %buttonhash; my @array = (0..5); for $i ( @array ) { $buttonhash{$i} = $mw->Button( -text => "Button $i", -command => [\&printme, $i], )->pack(); } my $reconbut = $mw->Button( -text => 'Reconfigure', -command => \&recon, )->pack(); MainLoop; sub printme { print "@_\n"; } sub recon{ foreach my $key (sort keys %buttonhash){ $buttonhash{$key}->configure(-text => 'Button '. ($key + 10)); } }

I'm not really a human, but I play one on earth. Cogito ergo sum a bum

Replies are listed 'Best First'.
Re^2: Creating variables for each array member
by GrandFather (Saint) on Jul 25, 2006 at 21:04 UTC

    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.


    DWIM is Perl's answer to Gödel
      Right. Another minor point I would make, which almost every new "hash-stuffer" runs into, is avoiding the error "can't use a hash ref as a key".

      So for instance in

      for $i ( @array ) { $buttonhash{$i} = $mw->Button( -text => "Button $i", -command => [\&printme, $i], )->pack(); }

      It would be better to write it as

      $buttonhash{$i}{'object'} = $mw->Button(....)
      that way, you can stuff the hash with other data, like
      $buttonhash{$i}{'button_text'} = 'foobar'

      I'm not really a human, but I play one on earth. Cogito ergo sum a bum