Putting Two MainWindows to Work

Here’s a trickier dual-display program that has been slightly obfuscated by removing comments and disguising subroutine names. Before we discuss it, try to figure out what it does. To orient yourself, realize that variables beginning with “l” mean “local,” and those beginning with “r” mean “remote.” You have 60 seconds. Okay, GO!

my $lmw = MainWindow->new;
my $rmw = MainWindow->new(-screen => $ARGV[0] ||= $ENV{DISPLAY});
my($le, $lt) = &create_widgets($lmw);
my($re, $rt) = &create_widgets($rmw);
&config_widgets($le, $lt, $re, $rt);
&config_widgets($re, $rt, $le, $lt); $rmw->bell;
MainLoop;

sub create_widgets {
    my $screen = shift;
    my $e = $screen->Entry->pack(qw/-fill x -expand 1/);
    $e->focus;
    my $t = $screen->Text(qw/-height 10/)->pack;
    ($e, $t);
}

sub config_widgets {
    my($le, $lt, $re, $rt) = @_;
    $le->bind('<Return>' => [sub {
        my($le, $lt, $re, $rt) = @_;
        $rt->tagConfigure(qw/blue -underline 1/);
        my $input = $le->get . "\n";
        $le->delete(0, 'end');
        $lt->insert('end' => $input);
        $rt->insert('end' => $input, 'blue');
    }, $lt, $re, $rt]);
}

...5, 4, 3, 2, 1...time’s up. Obviously, the key to understanding this program is the binding that config_widgets creates. (See Chapter 15 for more about bindings.)

Suppose Gromit is sitting in front of his Win32 computer and it happens to run an X server. In another part of the house, Wallace, an ever cheerful and willing-to-chat chap, runs our mystery program on his Linux box and specifies Gromit’s display on the ...

Get Mastering Perl/Tk now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.