Perl/Tk

As we discussed in Chapter 2, Perl was created by Larry Wall back in 1987. It is an extremely fast, interpreted scripting language that combines some of the best features of a variety of other languages, Perl is especially good at expression handling, scanning and manipulating text, and performing system management tasks.

Although some programmers prefer Perl and some prefer Tcl, everyone loves Tk. As we mentioned earlier, Tk was originally available only for Tcl, but in 1995, Nick Ing-Simmons (following up from Malcolm Beattie’s initial work at Oxford University) removed Tk’s original intrinsic need for Tcl and produced a much more portable set of code. He made this code directly acessible to many more languages, and it became known as pTk (portable Tk). As an encore, he wrapped this ported code in Perl, creating the Tk.pm Perl module. Thus, another open source star—Perl/Tk—was born.

Perl/Tk is an excellent scripted alternative to Tcl/Tk. If you’ve decided that the Perl DBI application interface is a good bet for quickly prototyping useful Oracle database tools and applications, then you’ll find that one of the best ways of wrapping them up is within a Perl/Tk GUI program. Aided and abetted by a growing army of evangelists (including the indefatigable Stephen Lidie), Perl/Tk has flowered into an amazing collection of widgets, fulfilling virtually every widget collector’s desire. Ing-Simmons’ development of the Tk800 port (encompassing Win32’s look-and-feel), combined with the robust growth of ActivePerl, means that Perl/Tk is now available on Solaris, Linux, and virtually every other flavor of Unix and Windows. Of course, the major benefit is that we can now use all of our Perl DBI/DBD::Oracle functionality within a superb GUI toolkit across a wide range of platforms.

These are the main web sites for Perl itself:

http://www.activestate.com

The ActiveState Win32 Perl portal site

The following are the main web sites for Perl/Tk:

http://www.xray.mpe.mpg.de/mailing-lists/ptk/
http://www.cpan.org/doc/FAQs/tk/ptkTOC.html
http://starbase.neosoft.com/~claird/comp.lang.perl.tk/ptkFAQ.html
http://www.pconline.com/~erc/perltk.htm
http://mysite.directlink.net/gbarr/PerlTk/tk-modlist.html

Unix and Win32 Perl

Perl’s origins were in the Unix world. However, Perl became very popular after Larry Wall released Version 1.0, and the tool soon outgrew its Unix roots. Windows developers started clamoring for access to Perl, which was fast becoming the “glue” language of the Internet. In 1995, in response to the market demand for Perl, Dick Hardt’s team at Hip Communications (the company that eventually morphed into ActiveState) created the first Win32 port of Perl. This port, with its many specific Win32:: Perl modules, gave most Windows NT administrators their first taste of Perl. As time went on, more and more modules were added, and Perl was well on its way to becoming the de facto scripting language of choice on Windows platforms. Win32 Perl became so successful, in fact, that there was a substantial risk that it would evolve away from the original mother tongue of Unix Perl. But Perl’s creator wasn’t about to let that happen. Fortunately for the rest of us, Larry stepped in at the decisive moment, drew Excalibur from the stone, and wielded it above the masses. He forced the two development communities to cooperate, and the kingdom thus became one again.

Those not familiar with Perl may wonder why it matters. What difference would it make if the Unix and Win32 Perls were different? In fact, it is this hard-won unity that gives Perl its power. You can write a single script on one operating system, and as long as you don’t use native methods, you can run it unchanged on every other kind of machine, from Linux to Windows NT through to Solaris and back again. That is a powerful advantage. Perl/Tk itself is an expression of this advantage. Because of Perl’s universality, Nick Ing-Simmons was able to create the Tk800 releases embodying a Win32 look-and-feel. Therefore, you can now run identical Perl GUI programs on virtually every type of operating system (we’ll say more about this later on).

Installing Perl/Tk over Perl 5

Chapter 2 explained how to install Perl and Perl DBI. Now we need to install Perl/Tk so we can start using this GUI toolkit to use and build Oracle applications.

Installing Perl/Tk on Unix

The following procedure should work with virtually all flavors of Unix:

  1. Download the latest Tk module available at the CPAN master site (or related mirror). This module will have a name in the form Tk800.xyz.tar.gz:

    ftp://ftp.funet.fi/pub/languages/perl/CPAN/modules/by-module/Tk/

  2. Unpack the tar file onto your machine.

  3. Change to the relevant directory and check through the README files to see if there’s anything specific to your operating system you need to know about.

  4. In most cases, you should be able to follow the usual Perl installation steps:

    $ perl Makefile.PL
    $ make
    $ make test
    $ make install

    The Perl/Tk install is perhaps one of the largest Perl modules you can build (aside from the main Perl distribution), and this procedure may take a few minutes to run. However, for those Perl enthusiasts who haven’t seen Perl/Tk before, the testing stage can be a memorable moment, as you’ll witness Perl GUIs popping onto the screen for the first time.

  5. When the installation is complete, look for the widget program in the .. /demos subdirectory, and run this to see what you now have available in the form of GUI Perl-driven widgets:

$ perl widget

Installing Perl/Tk on Windows

The process of installing Perl/Tk on Win32 systems is similar to installing the Perl DBI and DBD::Oracle ActiveState packages, as described in Chapter 2.

  1. Go to the following web site:

    http://www.activestate.com/Products/ActivePerl/status.html

  2. At around the 1050 mark, you’ll see the main Tk module, followed by many other extra Tk extensions. For now we’ll just pick up the main Tk module. If you want to experiment, you may want to pick up the rest later.

  3. Start up an MS-DOS control box and enter the PPM program:

    ppm
  4. Now install Tk at the PPM prompt:

    install Tk
  5. Enter “yes” to agree to the installation. Note that this is a large download and may take some time. Once this stage completes, however, with a burst of activity at the end, Perl/Tk is installed and you can quit out of PPM.

  6. Now that the setup is completed, you should be able to find and run the widget (or widget.bat) program under Windows, as shown in Figure 3-6 (notice that Ousterhout gets in the frame again because his original work was intrinsic to Perl/Tk, as well as to Tcl/Tk).

    cd C:Perlin
    perl widget
Running the Perl/Tk widget program under Win32

Figure 3-6. Running the Perl/Tk widget program under Win32

Installing Perl/Tk on Mac OS X

Rumors regularly scamper around the Perl/Tk mailing lists, suggesting that the port of Perl/Tk will be coming very soon to the new BSD Unix-related Macintosh operating system, Mac OS X. We’re betting that Stephen Lidie is sure to be involved when it does emerge; therefore, one of the best sites for keeping up with this kind of news is his own site:

http://www.lehigh.edu/~sol0/ptk/ptk.html

See also the other Perl/Tk sites listed earlier.

Program Structure in Perl/Tk

As with Tcl/Tk, the central reason why so many programmers like Perl/Tk is its speed of development. Whereas Java makes you write awkward mouse listeners and other modules that are prone to initial coding errors because of the volume and complexity of the code, Perl/Tk hides most of this nasty business of low-level control away from the script writer, letting you concentrate on the design.

A typical Perl/Tk program has three main steps (the last step, the simplest to code, also hides the most low-level programmatic difficulty):

  1. Create the main window.

    All of the widgets in a typical program are owned in a hierarchical tree, with the main window (conventionally called $mw or $top) created at the head of the tree.

  2. Build the required set of widgets.

    The widgets are configured, arranged, and packed as required by the application. These include menus, entry boxes, text widgets, sliding scales, canvases, buttons, labels, and many more. Where necessary, they are also tied to specific subroutines that are later called when the widget is manipulated in the appropriate manner (for example, when a button widget is pressed).

  3. Start the event loop.

    This is a fairly simple continuous loop that wakes up every few milliseconds to check if anyone has pressed a button or moved a scale along. It then responds accordingly, running any subroutine commands that have been tied to widgets in Step 2. In human time and on modern machines, it is unusual to notice any action delay.

Figure 3-7 demonstrates the typical structure and information flow within a Perl/Tk script. The crucial process is the attachment of the program EXIT step to a particular widget. As it’s looping every few milliseconds, the MainLoop( ) function accepts calls from the user’s mouse clicks or command line to run various subroutines. When the appropriate widget is eventually selected, the EXIT routine is called. The event loop then drops out, shutting down the program in the process. Most windowing systems will generally allow you to shut down a window at the operating system level, usually by clicking an “X” symbol at the top right of the main window, but in full-featured applications, you’ll often want to tie a button to this task as well, just to make things more straightforward for the user.

Connecting Perl/Tk to Oracle

Now that we’ve explained at least the basics of Perl/Tk, let’s turn to Perl DBI and get down to some real honest Oracle connectivity. Like Perl DBI, the Tk module itself is “just another” Perl module, and it is treated as such. Getting back to our starship, we already have a program in Engineering controlling our “Crystallofusion” warp drive and supplying the necessary power. What we need now is a similar startup program for the baggy-suited, V-necked technician in the Transporter Room to slide up and down to get us to the planet below. Let’s try to write one in Perl/Tk, shown in Example 3-4, as a precursor to our look at OraExplain (an excellent Oracle application based on Perl/Tk that we’ll examine later in this chapter).

Typical three-part program structure within a Perl/Tk script

Figure 3-7. Typical three-part program structure within a Perl/Tk script

Example 3-4. A Simple Perl/Tk Example

#!/usr/local/bin/perl -w

# transporter.pl

# Step 1: Get Tk and create the main window.

use Tk;

my $mw = MainWindow->new(-title=>'Transporter'),

# Step 2: Build up our collection of widgets and 
# pack them onto the screen.

$mw->Button(-text=>"Control Sliders")->pack(-side=>'top'),

$mw->Scale(-label=>"Fuzz")->pack(-side=>'left'),
$mw->Scale(-label=>"Spark")->pack(-side=>'left'),
$mw->Scale(-label=>"Pop")->pack(-side=>'left'),

# Step 3: Set the main loop action listener running.

MainLoop(  );

Once again, this is a pretty straightforward example, consisting of one button and three sliding scales. The resulting screen is displayed in Figure 3-8 (which also demonstrates the Win32 look-and-feel port of Tk). The main difference between this script and the related Tcl script we showed earlier is the use of Perl 5’s intrinsic object orientation (hinted at with the use of the “->” arrow notation). Notice also that the top-level widget and main window screen, $mw, is heading a hierarchy of subservient widgets that drop off it like spiders from a web.

This hierarchical control and heavy use of object orientation give Perl/Tk an enormous amount of power within small amounts of code, as witnessed in the pretty spartan Example 3-4. Once the required widgets are packed and configured, the MainLoop( ) function takes over all the mouse listening and action running commitments.

The GUI created by transporter.pl for Linux and Win32

Figure 3-8. The GUI created by transporter.pl for Linux and Win32

There is a lot more to the Perl/Tk module, but rather than take you on a general widget tour, we’ll get straight into one of the first Perl/Tk Oracle applications.

OraExplain

As we mentioned previously, when you download DBD::Oracle, you’ll find the OraExplain program within the download. This program, developed by Alan Burlison, was one of the first widely available programs to use both Perl DBI and Perl/Tk together. OraExplain lets you examine your SQL cache and operate Oracle’s EXPLAIN PLAN facilities. You can drill down into the detail of any SQL you wish to investigate, including that in the cache, and your investigations may help you tune your queries.

Although ActivePerl Win32 users don’t normally need the full DBD::Oracle download (since their DBI needs are supplied by binary packages available via PPM), if they want OraExplain, they need to visit the relevant CPAN DBD page and download the full DBD::Oracle tarball, as described in Chapter 2. Once it has been downloaded and unzipped with a program such as WinZip, you’ll see the OraExplain program within the tar file. OraExplain can then be copied out to the normal operating system.

Perl/Tk and Perl DBI combined

The OraExplain code in Example 3-5 is used to create the login dialog screen (we’ve added step numbers as comments, for later reference). You can see the resulting login dialog at the top left side of Figure 3-9.

Example 3-5. Login Dialog Code from OraExplain

sub login_dialog($)
{
my ($parent) = @_;

# Create the dialog
if (! $LoginDialog)
   {
   my $username = "/";
   my $password = "";
   my $database = $ENV{TWO_TASK} || $ENV{ORACLE_SID};

   # Step 1

                     $LoginDialog = $parent->Toplevel(-title => "Login to Oracle");
   $LoginDialog->withdraw(  );
   $LoginDialog->resizable(0, 0);
   my $box;

   # Create the entry labels & fields
   $box = $LoginDialog->Frame(-borderwidth => 1, -relief => "raised");
   $box->Label(-text => "Username")
      ->grid(-column => 0, -row => 0, -sticky => "w");
   $box->Entry(-textvariable => $username, -width => 30)
      ->grid(-column => 1, -row => 0, -sticky => "w");
   $box->Label(-text => "Password")
      ->grid(-column => 0, -row => 1, -sticky => "w");
   $box->Entry(-textvariable => $password, -width => 30, -show => "*")
      ->grid(-column => 1, -row => 1, -sticky => "w");
   $box->Label(-text => "Database")
      ->grid(-column => 0, -row => 2, -sticky => "w");
   $box->Entry(-textvariable => $database, -width => 30)
      ->grid(-column => 1, -row => 2, -sticky => "w");
   $box->pack(-expand => 1, -fill => "both", -ipadx => 6, -ipady => 6);

   # Step 2

   # Create the buttons & callbacks
   $box = $LoginDialog->Frame(-borderwidth => 1, -relief => "raised");
   my $cb = sub
      {

      # Step 4 - Note this is called by Step 3 below.

      if (! eval { login($database, $username, $password); })
         {
         error($parent, $@);
         $LoginDialog->raise($parent);
         }
      else
         {
         update_title(  );
         $LoginDialog->withdraw(  );
         }
      };

   # Step 3 - Note the command $cb, mentioned above in Step 4.

   $box->Button(-text => "Login", -default => "active",-command => $cb)
      ->pack(-side => "left", -expand => 1, -pady => 6);
   $box->Button(-text => "Cancel", 
                -command => sub { $LoginDialog->withdraw(  ) })
      ->pack(-side => "right", -expand => 1, -pady => 6);
   $box->pack(-expand => 1, -fill => "both");

   # Step 5

   $LoginDialog->bind("<KeyPress-Return>", $cb);
   }
# Activate the dialog
$LoginDialog->Popup(  );
}

Here’s what’s happening in Example 3-5:

  1. A top-level widget screen $LoginDialog is formed, and then a short entry form is packed into the first frame for you to enter a username, password, and database connection string. These are stored in backslash-referenced text variables that have corresponding names.

  2. The bottom half of the dialog screen is then formed within a second frame, as well as a callback subroutine, $cb, which is predefined for later use. This callback is set to call a further login( ) function (not detailed here), which will set up the actual database connection handle.

  3. Two action buttons, Login and Cancel, are then packed into this second frame, with the Login button tied via -command to the callback function $cb. (Although this sounds so far like a soap opera plot, don’t despair—we’re nearly there.)

  4. When you press the Login button, the login( ) function within $cb is evaluated with Perl’s very handy eval function, ideal for trapping errors. On success, the Login Dialog will withdraw to the shadows, to return later when required. You now get access to the main screen—and away you go.

  5. You may also notice the <KeyPress-Return> notation, which, when you press the Return key at any time, will attempt to connect you via the callback function to the desired database.

Once you’ve successfully logged in, ora_explain.pl lets you examine your SQL cache, use Oracle’s EXPLAIN PLAN facilities, and perform a variety of other useful Oracle functions. Drill down into the various menu options and see for yourself.

The login dialog and other main screens of OraExplain

Figure 3-9. The login dialog and other main screens of OraExplain

We’re great fans of OraExplain. It’s an excellent Oracle analysis and tuning tool, and it also provides a solid example of an Oracle Perl/Tk open source application on which developers can base their own Perl/Tk applications. We’ll examine another Perl/Tk DBI Oracle application in detail in Chapter 4.

Before we leave Perl/Tk and head on into Python territory, however, we’ll just mention an exciting tool that could soon bring Perl/Tk to an Internet site near you.

Perlplus Plug-in

The Java Virtual Machine (JVM) is built into most current browsers, but it’s not the only solution for running applications over the Web. If you’re prepared to do a little extra work ahead of time, you can now also get Perl/Tk applications running over the Internet using the Perlplus Netscape plug-in, a Perl solution developed by Frank Holtry (with the help of Stephen Lidie and based upon original work by Stan Melax). Perlplus is similar in concept to some of the commercially available Tcl/Tk web plug-ins.[25] With heavy security built into it, Perlplus now runs under Solaris, Linux, and Windows, plus a host of other Unix variants. While still largely experimental (it’s in the 0.95 version stage), Perlplus is developing rapidly towards the magical 1.0 release and already gives you a flavor of what will be possible soon.

The following are the main web sites for Perlplus:

http://www.perl.com/CPAN-local/modules/by-authors/id/F/FH/FHOLTRY/

The main download site for the Perlplus plug-in

http://home.rmi.net/~fholtry/

Frank Holtry’s home page, where you can check out the latest on Perlplus and await the first out-of-the-box configurable releases for Unix and Windows

Installing Perlplus on Linux

The Perlplus program is as close to the leading edge as we come in this book, so there is not yet a Perl-style configuration program. It’s bare knuckle time if you want to try installing Perlplus. The gzipped package from CPAN will contain the latest instructions; we’ll summarize the steps here:

  1. Download the Perlplus plug-in source code.

  2. Configure Perlplus by following the detailed instructions in the INSTALL file. In particular, see the discussion of compiler directives and environment variables. The most important of these is SECURE_CGI, which directs the plug-in to a specific CGI script later authorizing the security of any future Perl script run by Perlplus. (Extra notes are supplied, in the README.Win32 file in the installation package, for compiling Perlplus with commercial Visual C++ compilers on Win32.) We employed the following configuration (which also assumed our local web server was running on port 8000):

    DEBUG=0
    PERL5005=1
    PERL_ROOT=/usr
    PERL_EXE=${PERL_ROOT}/bin/perl
    OPTIMIZER=-O
    MY_CFLAGS=${OPTIMIZER}
    MIME="application/x-perlplus:.ppl:Perl"
    CGI_TYPE="Content-type:
    application/x-secure-cgi
    Content-length:"
    SECURE_CGI="http://127.0.0.1:8000/cgi-bin/perlplus-secure.cgi"
    INCLUDES=/usr/include
    RM=/bin/rm
  3. Next, clean up any old compilations (if you have any), compile afresh, and install the plug-in with a statement that depends on your operating system (such as Linux, Irix, or Solaris). The plug-in itself will be automatically transferred to your $HOME/.netscape/plugins directory:

    $ make clean
    $ make linux
    $ make install
  4. Configure the Apache web server (Apache is covered in Chapter 5) to accept the MIME-type application/x-perlplus and *.ppl files types. We added this line to the mime.types file in the Apache .. /conf directory:

    application/x-perlplus   ppl
  5. Now update the Netscape browser (choose Edit Preferences from the menu, then Navigator Applications in the left pane of the Preferences dialog) to link the application/x-perlplus MIME-type plug-in with the usual Perlplus script extension, *.ppl. (Full instructions for doing this, along with everything else here, are also contained within the Perlplus INSTALL file.)

  6. Use a CGI script perlplus-secure.cgi to verify the security of the called scripts. In this example on 127.0.0.1, we employed a simplified version:

    #!/bin/sh
    # perlplus-secure.cgi
    echo  "Content-type:
    application/x-perlplus:.ppl:Perl
    "
    sec_level=1
    echo  "$sec_level"
  7. Move this CGI script to your Apache web server’s CGI bin, along with one of Frank Holtry’s sample applications, which you’ll also find in the Perlplus download. (We chose ptk_test.ppl because it was the first one we ever saw, and mighty impressive it was at the time, too.)

  8. From the Apache web server home page, call up this Perlplus example program, as we’ve done in Figure 3-10.

We’ll say more about Perlplus again in the next chapter, when we show how to connect the Orac application (built with Perl/Tk and Perl/DBI) to the Internet.



[25] We’re hoping that the Perlplus plug-in will perhaps come prebuilt with Perl/Tk at some near-future point (as the PVM—Perl Virtual Machine?).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset