Module Design and Implementation
Now the subroutine can be called like this:
($status, $reply) = hobnob("Hello out there!");
This style makes it obvious that both $status and $reply are values returned by the
subroutine.
Consider allowing your routines to behave differently in list and scalar context
using the wantarray() built in. It's much easier to use a subroutine that knows to
return a count of its results in scalar context than to have to assign the results to an
array and take its length. This also allows you to mimic the way many Perl built ins
use context to determine their behavior (such as localtime and split). Here's a
subroutine that returns all the values currently in a message queue in list context
and the number of messages in scalar context:
sub get_messages {
if (wantarray) {
return @MESSAGES; # return all the messages in list context
} else {
return $MESSAGE_COUNT; # return the message count in scalar context
}
}
Using the Exporter
Many functional modules will use the Exporter to make their subroutines available
in the user's package. This is very convenient, but doing it in the simplistic way
presented in the last chapter has some drawbacks. To refresh your memory, the
simplest way to use the Exporter is to export everything by default:
package BOA::Network;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(open_socket
send_message
receive_message
close_socket
start_server
stop_server);
With this setup it's possible to selectively import just the symbols you need:
use BOA::Network qw(open_socket send_message close_socket);
79
79
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