Closures in Action

#!/usr/bin/perl -w

use strict;
use Gtk2 -init;
use Glib qw(TRUE FALSE);

create_gui();

Gtk2->main;

exit;

sub create_gui {
  my $window = Gtk2::Window->new;
  $window->signal_connect(
    delete_event => sub { Gtk2->main_quit; }
  );

  my $vbox = Gtk2::VBox->new();
  $vbox->set_border_width(12);
  $window->add($vbox);

  my $label = Gtk2::Label->new;
  $label->set_markup(
    '<span foreground="black">Hello World!</span>'
  );
  $vbox->pack_start($label, TRUE, TRUE, 4);

  add_button($vbox, 'Red',   $label);
  add_button($vbox, 'Green', $label);
  add_button($vbox, 'Blue',  $label);

  $window->show_all;
}

sub add_button {
  my($vbox, $label, $target) = @_;

  my $button = Gtk2::Button->new($label);
  $button->signal_connect(
    clicked => sub { set_label_color($target, lc($label)); }
  );
  $vbox->pack_start($button, TRUE, TRUE, 4);
}

sub set_label_color {
  my($target, $colour) = @_;

  my $markup = $target->get_label;
  $markup =~ s/foreground=".*?"/foreground="$colour"/;
  $target->set_markup($markup);
}