A Matter of (Indirect) Syntax - Page 171
May 21, 2001
Thus far we've called object methods using the arrow, or ->,
syntax. While popular and attractive, you may sometimes see
scripts or documentation that uses indirect object syntax.
One of the more common examples is the indirect constructor, for
example when creating a CGI object:
my $cgiobj = new CGI;
This indirect syntax specifies the method name first, followed by
the class or object name, and finally any parameter list if
available. Using the indirect syntax, we could replace our
earlier call to header(-expires=>'-1d') with:
print STDOUT header $cgiobj (expires=>'-1d');
In one sense, the indirect syntax is just that: indirect, and
thus less clear. Why would anyone prefer the above? But here's a
neat trick — using the indirect syntax, you can
substitute an expression for the class or method name. In doing
do, you can in fact both create and use the object in a single
statement:
print STDOUT header {new CGI} (expires=>'-1d');
Most of the time, the parentheses can be omitted from the
parameter list when using indirect syntax, but at the peril of
further obtuseness. While this author generally endorses the
arrow, rather than indirect, syntax, there are times when
indirect is indeed more intuitive, such as with the new object
constructor.
Black Box Restated
There isn't much to it — using objects, that is. And
that's the whole point of the little black box, so long as you
know how to pull its levers and twiddle its knobs. Many Web
developers may never create object classes themselves, but will
likely use them as created by others, and propagated as Perl
modules. In practice, this is the most important skill, along
with understanding just why object orientation is so useful
(points we covered early on).
Still, the thirsty and inquisitive minds of Perl developers may
hunger for more. It's not enough to learn how to drive the car
— we want to know how to build a car! Creating classes and
objects is, of course, slightly more complicated than using them,
but no less fulfilling. Next time we look at object orientation
in Perl, we'll go under the hood, as it were, and begin building
object classes of our own, for both our own enjoyment and the
enjoyment of others.
Classism - Page 170
The Perl You Need to Know
|