http://www.perlmonks.org?node_id=208407

Update {Please note the code at RFC: Class::Proxy::MethodChain that spun off of this snippet later and my eventual conclusion at Re: RFC: Class::Proxy::MethodChain. This code is far too elaborate an effort for something that can be had much easier; consider it an educational example, but don't go using it (in exactly this form). }

I've been doing some Gtk work lately, and if you've ever done so you'll know that code tends to turn into long runs of method calls against the same just instantiated widget, like:

my $btn = Gtk::Button->new("Quit"); $btn->signal_connect(clicked => sub { Gtk->exit(0); return }); $btn->show; my $window = Gtk::Window->new("toplevel"); $window->signal_connect(delete => sub { Gtk->exit(0); return }); $window->set_title("Test"); $window->border_width(15); $window->add($btn); $window->show;
You can imagine how bad it gets when there are 30 widgets distributed across four different containers, each object needing a dozen method calls to configure. With the following snippet, you can write this as
my $window = configure_object( Gtk::Window->new("toplevel"), signal_connect => [ delete => sub { Gtk->exit(0); return } ], set_title => [ "Test" ], border_width => [ 15 ]; add => [ configure_object( Gtk::Button->new("Quit"), signal_connect => [ clicked => sub { Gtk->exit(0); return } ], show => undef, )], show => undef, );

which I find much nicer. It lets you omit a lot of otherwise necessary temporary variables, and it also makes it clear - by way of nesting - which widgets are inserted where. In contrast, the flat structure requires you to search on the names of temporary widget variables to figure out how they all relate to each other.

It also has provision to deal with multilevel calls which are necessary for some objects:

$fileselect->cancel_button->signal_connect( clicked => sub { $fileselect->hide } ); # ...
becomes
configure_object( $fileselect, cancel_button => signal_connect => [ clicked => sub { $fileselect->hide }, ], # ... );
sub configure_object { my $object = shift; while(@_) { my ($meth, $param) = splice @_, 0, 2; my $obj = $object; until((not defined $param) or ref $param) { $obj = $obj->$meth; ($meth, $param) = ($param, shift); } $obj->$meth(@{ $param || [] }); } return $object; }