Easy Perl5 Object Intro
Some people shy away from highly convenient Perl5 modules
because they sometime deal with objects. And while the managers
haven't figured it out yet, the programmers realize that
objects are too often used to make something overly complicated
without providing much realistic increased usefulness.
On the other hand, some problems very much lend themselves to
objects. This scares people. It shouldn't.
There's a tremendous difference between merely knowing enough OO
programming enough to merely use someone else's modules versus enough
to actually design and implement one yourself. People are afraid of
the having to be the latter just to get at the former. This is far
from the case.
There isn't much to using an object module. You merely load in the
library, and then call its documented ``constructors'', things that build
new objects, often called new().
If you haven't used perl5 before, you just need to brush up on
at most one or two new concepts that you wouldn't have seen before.
Here they are:
- The use Module statement will load in a module called Module.pm (at compile time) and import its exported
names into your namespace. The statement require Module also loads it, but only at
run time, and doesn't do any imports.
- The -> dereferencing arrow is to call a method on an object. You might
think of it as sending a message to that object. You don't need to
know what's in an object. It's just a black box thingamawhatzitz
that you can call methods on. That's it.
- The following two lines are equivalent. The second mechanism
is less syntactically ambiguous, however.
$obj = new CGI;
$obj = CGI->new():
- Like any other subroutine call, a method call may return
anything it wants, even another object.
use LWP::UserAgent;
$ua = new LWP::UserAgent;
$ua->agent("Mozilla/5.0PlatinumB3"); # hee :-)
$req = new HTTP::Request GET => 'http://perl.com/perl/';
$req->header('Accept' => 'text/html');
# send request
$result = $ua->request($req);
# check the outcome
if ($result->is_success) {
print $result->content;
} else {
print "Error: " . $result->code
. " " . $result->message;
}
Bingo. EOStory. That's all folks. That's all you need to to know to use
object in Perl. No great magic. How hard can it be?
Here are some examples of using the perl WWW modules.
use CGI;
$req = CGI->new();
use CGI::Imagemap;
$map = CGI::Imagemap->new();
use HTML::Parse;
$html = parse_htmlfile("test.html");
use URI::URL;
$url = URI::URL->new('gisle.gif','http://www.com/%7Euser');
use HTTP::Request;
$hreq = HTTP::Request->new('GET', 'http://www.perl.com/');
I am not convinced you to need to be a smalltalk and C++ superguru
to deal with this stuff. But if you do what to learn more,
you might check out the perlobj manpage.
Return to:
Copyright 1996 Tom Christiansen.
All rights reserved.