Rudif has asked for the wisdom of the Perl Monks concerning the following question:
Suppose that I want to adapt an existing class to my immediate needs, by adding some methods, right in my quick and not-too-dirty script.
I can see two ways, illustrated below, with Tk::HList::addrow() and updaterow().
Please comment on pros and cons, and on other possible ways to achieve this.
#!/usr/bin/perl use strict; use Tk; use Tk::Label; use Tk::HList; sub Tk::HList::addrow { my ( $self, $row, $text ) = @_; $self->add($row); $self->itemCreate( $row, 0, -text => $text ); } package Tk::HList; sub updaterow { my ( $self, $row, $text ) = @_; $self->itemConfigure( $row, 0, -text => $text ); } package main; my @items; my $selectedrow = 0; my @text = qw ( AAA BBB CCC DDD EEE FFF ); my $mw = MainWindow->new(); my $frm1 = $mw->Frame()->pack( -side => 'top', -anchor => 'w' ); my $frm2 = $mw->Frame()->pack( -side => 'top', -anchor => 'w' ); my $but1 = $frm1->Button( -text => "reverse", -command => \&revers, -width => 20, )->pack( -side => 'left' ); my $label = $frm2->Label( -width => 5, -text => $selectedrow )->pack( -side => 'left' ); my $but2 = $frm2->Button( -text => "incr", -command => \&incr, -width => 15, )->pack( -side => 'left' ); my $hlist = $mw->HList( -itemtype => 'text', -height => 20, -separator => '/', -selectmode => 'single', -browsecmd => sub { $selectedrow = shift; $label->configure( -text => $selectedrow ); print "$selectedrow\n"; } )->pack; add(); MainLoop; sub add { foreach my $i ( 0 .. $#text ) { $hlist->addrow( $i, $text[$i] ); push @items, $i; } } sub refresh { foreach my $i ( 0 .. $#text ) { $hlist->updaterow( $i, $text[$i] ); } } sub incr { ++$text[$selectedrow]; refresh(); } sub revers { @text = reverse @text; refresh(); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Reopen a class, add methods ?
by ikegami (Patriarch) on May 13, 2007 at 02:03 UTC | |
by Rudif (Hermit) on May 13, 2007 at 15:27 UTC | |
|
Re: Reopen a class, add methods ?
by friedo (Prior) on May 12, 2007 at 22:48 UTC | |
by Rudif (Hermit) on May 13, 2007 at 15:21 UTC | |
|
Re: Reopen a class, add methods ?
by Joost (Canon) on May 12, 2007 at 22:50 UTC | |
by ikegami (Patriarch) on May 13, 2007 at 01:58 UTC |