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.


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^3: Creating variables for each array member
by zentara (Cardinal) on Jul 26, 2006 at 12:29 UTC
    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