Create context-senstive return values
Usually, when you need to create a subroutine that returns different values
in different contexts (list, scalar, or void), you write something like:
sub get_server_status {
my ($server_ID) = @_;
# Acquire server data somehow...
my %server_data = _ascertain_server_status($server_ID);
# Return different components of that data,
# depending on call context...
if (wantarray()) {
return @server_data{ qw(name uptime load users) };
}
if (defined wantarray()) {
return $server_data{load};
}
if (!defined wantarray()) {
carp 'Useless use of get_server_status() in void context';
return;
}
else {
croak q{Bad context! No biscuit!};
}
}
That works okay, but the code could certainly be more readable. In its
simplest usage, this module makes that code more readable by providing
three subroutines--'LIST()', 'SCALAR()', 'VOID()'--that are true only when
the current subroutine is called in the corresponding context:
use Contextual::Return;
sub get_server_status {
my ($server_ID) = @_;
# Acquire server data somehow...
my %server_data = _ascertain_server_status($server_ID);
# Return different components of that data
# depending on call context...
if (LIST) { return @server_data{ qw(name uptime load users) } }
if (SCALAR) { return $server_data{load} }
if (VOID) { print "$server_data{load}\n" }
else { croak q{Bad context! No biscuit!} }
}
- Developed at devel:languages:perl
- Sources inherited from project openSUSE:Factory
-
2
derived packages
- Download package
-
Checkout Package
osc -A https://api.opensuse.org checkout openSUSE:Factory:Rebuild/perl-Contextual-Return && cd $_
- Create Badge
Source Files
Filename | Size | Changed |
---|---|---|
Contextual-Return-0.004001.tar.gz | 0000038204 37.3 KB | |
perl-Contextual-Return.changes | 0000001035 1.01 KB | |
perl-Contextual-Return.spec | 0000003539 3.46 KB |
Revision 5 (latest revision is 17)
- updated to 0.004001 - Updated version number of Contextual::Return::Failure to placate CPAN indexer - Improved error messages for bare handlers in bad contexts (thanks Mathew) - Work around problems with Test::More and caller - Fixed context propagation bugs in FIXED and ACTIVE modifiers - Added STRICT modifier to prevent fallbacks (i.e. impose strict typing on return values) - Fixed annoying POD nit (thanks Salvatore)
Comments 0