in reply to multiple method calls against the same object, revisited
For what it's worth, I think I prefer this syntax:
my $window = Gtk2::Window->new( "toplevel" )->call_method_list( signal_connect => [ delete_event => sub { Gtk2->main_quit } ], set_title => "Test", set_border_width => 15, add => Gtk2::Button->new( "Quit" )->call_method_list( signal_connect => [ clicked => sub { Gtk2->main_quit } ] ), 'show_all', );
Implementation follows:
use Carp qw( croak ); sub UNIVERSAL::call_method_list { my $target = shift; while ( scalar @_ ) { my $method = shift @_; my @args = (! scalar @_) ? () : (ref($_[0]) eq 'ARRAY') ? @{shift} + : shift; eval { $target->$method( @args ) }; if( $@ ) { croak( $@ ) } } return $target; }
P.S.: Unfortunately, if( $@ ) { require Carp; Carp::croak( $@ ) } won't work the way you want it to, because if Carp hasn't already been required, the process of loading it clears $@, so it's not available to the croak call. You could write it as if ( my $err = $@ ) { ... croak( $err) } but I think that in practice this technique will only be used in larger, non-trivial applications, so you might as well just require Carp up front.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: multiple method calls against the same object, revisited
by Aristotle (Chancellor) on Dec 28, 2004 at 09:51 UTC | |
by eric256 (Parson) on Dec 28, 2004 at 18:33 UTC | |
by Aristotle (Chancellor) on Dec 28, 2004 at 22:10 UTC | |
by eric256 (Parson) on Dec 28, 2004 at 23:14 UTC | |
by dragonchild (Archbishop) on Dec 28, 2004 at 18:35 UTC | |
by eric256 (Parson) on Dec 28, 2004 at 19:30 UTC | |
Re^2: multiple method calls against the same object, revisited
by ihb (Deacon) on Dec 28, 2004 at 02:44 UTC | |
by simonm (Vicar) on Dec 28, 2004 at 07:48 UTC |
In Section
Cool Uses for Perl