Chapter 2
types, it's not likely you'll be overloading addition in your modules. On the other
hand, overloading conversion is quite common. An overloaded conversion
operator is called when Perl wants to use your object in a particular context
string, numeric, or Boolean.
Overloading string conversion enables you to provide a method that Perl will
call when it wants to turn your object into a string. Here are a few examples of
places where a string conversion operator is used:
$string = "$object";
$string = "I feel like a " . $fly . " with its wings dipped in honey.";
print "Say hello to my little ", $friend, ".\n";
Without an overloaded string conversion operator, objects are converted to
highly esoteric strings such as IO::File=GLOB(0x8103ee4) just next door to
useless. By providing a string conversion operator, a class can furnish a more
useful string representation. This can enhance debugging and provide a simpler
interface for some modules.
For example, one of my fellow BOA programmers is an exceptionally lazy indi
vidual. He's responsible for the networking code in BOA::Network. Each network
connection is represented as an object in the BOA::Network class. Since he's
such a lazy guy, he'd like to be able to use the BOA::Logger class with the absolute
minimum work:
$logger >write(1, $connection);
His initial suggestion was that I modify write() to check for BOA::Network objects
and pull out the relevant status information for logging. That would work, but
sooner or later you'd have an if() for every module in BOA. Because BOA is a big
ol' application, this wouldn't be a good idea. Instead, BOA::Network can overload
string conversion:
package BOA::Network;
use overload "" => "stringify";
sub stringify {
my $self = shift;
return ref($self) . " => read $self >{read_bytes} bytes, " .
"wrote $self >{wrote_bytes} bytes at " .
"$self >{kps} kps";
}
50
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved