Structure of a wxPerl program

The general structure of a wxPerl program has a strong object-oriented form, consisting of at least three individual classes. When defining a class, we prefer to use the package block syntax, which was introduced in Perl 5.14. For this reason we include the line “use 5.14;” at the top of the program. 

The first class defines a frame that is usually inherited from the Wx::Frame class. In wxPerl, frames are toplevel windows and constitute the foundation on which all other GUI elements are built on. Frames are discussed in much greater detail in “Part II - The wxPerl Widgets”. The key feature of this frame class is that all widget objects created are stored in the frame object itself. In this book, we will always refer to the frame object as “$self”. When widgets are created, you will typically see the following syntax used,
	$self->{widget_name} = Wx::WidgetClass->new( ... );
The reason for storing widget objects in this manner will become clear later on.

The second class defines the application, and is always inherited from the Wx::App class. The main purpose of the application class is to define a subroutine called OnInit(). This subroutine is responsible for creating all the widgets and layouts that define the GUI of your application.

The third class creates the application by instantiating an object of the application class and placing it into the event loop. The class method MainLoop() is responsible for registering and adding the application into the event loop.

	#!/usr/local/bin/perl

	use 5.14;

	package MyFrame {
		use strict;
		use warnings;
		use base qw( Wx::Frame );
		use Wx   qw( :everything );

		sub new {
			my ($class, $parent) = @_;

			my $self = $class->SUPER::new( $parent,
	wxID_ANY,
	"Frame Title",
	wxDefaultPosition,
	wxDefaultSize );

			$self->{MainPanel} = Wx::Panel->new($self, wxID_ANY);

			return($self);
		}
	}

	package MyApp {
		use strict;
		use warnings;
		use base qw( Wx::App );

		sub OnInit {
			MyFrame->new()->Show(1);
		}
	}

	package main {
		use strict;
		use warnings;

		MyApp->new()->MainLoop();
	}

Listing 1. The general structure of a wxPerl program