Re: Passing values to CodeRefs



This is a subtle, but large, difference between
   $widget->signal_connect(clicked => sub { rankChanged($arg1, $arg2) });
and
   $widget->signal_connect(clicked => \&rankChanged, [ $arg1, $arg2 ]);

This is due to the fact that the first is closure and the second is
not.  This leads to two major differences in behaviour:

1. the parameters are different

sub rankChanged { #version using the closure
   my ($arg1, $arg2) = @_;
   .
   .
   .
}

sub rankChanged { #other version
   my ($widget, $args) = _;
   my ($arg1, $arg2) = @$args;
   .
   .
   .
}

2. in the closure, the variables are captured (changes in the variable
will be seen by the calling function)

Variables inside of a closure are "alive".  Changes to the contents
are reflected in future calls.  I wrote this little program to
demonstrate the behaviour.  Clicking on the button named "data" will
cause it to fill the label with its version of the contents of $text.
Clicking on "closure" will cause it to fill the label with the current
version of the contents of $text (which is being changed by a
timeout).

#!/usr/bin/perl

use strict;
use warnings;

use Gtk2;

Gtk2->init;

my $w       = Gtk2::Window->new;
my $vbox    = Gtk2::VBox->new;
my $label   = Gtk2::Label->new;
my $hbox    = Gtk2::HBox->new;
my $closure = Gtk2::Button->new('Closure');
my $data    = Gtk2::Button->new('Data');

my $text    = "Hello!";

$w->add($vbox);
$vbox->add($label);
$vbox->add($hbox);
$hbox->add($closure);
$hbox->add($data);

$w->signal_connect('destroy' => sub { Gtk2::main_quit});
$closure->signal_connect('clicked' => sub { modify_text($closure,
[$label, $text]) });
$data->signal_connect('clicked' => \&modify_text, [$label, $text]);

my $orig = $text;
Glib::Timeout->add(1000, sub { $text = "$orig " . localtime(); 1});

$w->show_all;

Gtk2->main;

sub modify_text {
       my ($button, $args) = @_;
       my ($label, $text) = @$args;
       $label->set_text($text);
}



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]