.\" Automatically generated by Pod::Man 4.07 (Pod::Simple 3.32) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .if !\nF .nr F 0 .if \nF>0 \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} .\} .\" ======================================================================== .\" .IX Title "Contextual::Return 3pm" .TH Contextual::Return 3pm "2017-06-17" "perl v5.24.1" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Contextual::Return \- Create context\-sensitive return values .SH "VERSION" .IX Header "VERSION" This document describes Contextual::Return version 0.004014 .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 2 \& use Contextual::Return; \& use Carp; \& \& sub foo { \& return \& SCALAR { \*(Aqthirty\-twelve\*(Aq } \& LIST { 1,2,3 } \& \& BOOL { 1 } \& NUM { 7*6 } \& STR { \*(Aqforty\-two\*(Aq } \& \& HASHREF { {name => \*(Aqfoo\*(Aq, value => 99} } \& ARRAYREF { [3,2,1] } \& \& GLOBREF { \e*STDOUT } \& CODEREF { croak "Don\*(Aqt use this result as code!"; } \& ; \& } \& \& # and later... \& \& if (my $foo = foo()) { \& for my $count (1..$foo) { \& print "$count: $foo is:\en" \& . " array: @{$foo}\en" \& . " hash: $foo\->{name} => $foo\->{value}\en" \& ; \& } \& print {$foo} $foo\->(); \& } .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" Usually, when you need to create a subroutine that returns different values in different contexts (list, scalar, or void), you write something like: .PP .Vb 2 \& 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 \*(AqUseless use of get_server_status() in void context\*(Aq; \& return; \& } \& else { \& croak q{Bad context! No biscuit!}; \& } \& } .Ve .PP 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\*(--\f(CW\*(C`LIST()\*(C'\fR, \f(CW\*(C`SCALAR()\*(C'\fR, \f(CW\*(C`VOID()\*(C'\fR\-\-that are true only when the current subroutine is called in the corresponding context: .PP .Vb 1 \& 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}\en" } \& else { croak q{Bad context! No biscuit!} } \& } .Ve .SS "Contextual returns" .IX Subsection "Contextual returns" Those three subroutines can also be used in another way: as labels on a series of \fIcontextual return blocks\fR (collectively known as a \fIcontextual return sequence\fR). When a context sequence is returned, it automatically selects the appropriate contextual return block for the calling context. So the previous example could be written even more cleanly as: .PP .Vb 1 \& 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... \& return ( \& LIST { return @server_data{ qw(name uptime load users) } } \& SCALAR { return $server_data{load} } \& VOID { print "$server_data{load}\en" } \& DEFAULT { croak q{Bad context! No biscuit!} } \& ); \& } .Ve .PP The context sequence automatically selects the appropriate block for each call context. .SS "Lazy contextual return values" .IX Subsection "Lazy contextual return values" \&\f(CW\*(C`LIST\*(C'\fR and \f(CW\*(C`VOID\*(C'\fR blocks are always executed during the \f(CW\*(C`return\*(C'\fR statement. However, scalar return blocks (\f(CW\*(C`SCALAR\*(C'\fR, \f(CW\*(C`STR\*(C'\fR, \f(CW\*(C`NUM\*(C'\fR, \&\f(CW\*(C`BOOL\*(C'\fR, etc.) blocks are not. Instead, returning any of scalar block types causes the subroutine to return an object that lazily evaluates that block only when the return value is used. .PP This means that returning a \f(CW\*(C`SCALAR\*(C'\fR block is a convenient way to implement a subroutine with a lazy return value. For example: .PP .Vb 6 \& sub digest { \& return SCALAR { \& my ($text) = @_; \& md5($text); \& } \& } \& \& my $digest = digest($text); \& \& print $digest; # md5() called only when $digest used as string .Ve .PP To better document this usage, the \f(CW\*(C`SCALAR\*(C'\fR block has a synonym: \f(CW\*(C`LAZY\*(C'\fR. .PP .Vb 6 \& sub digest { \& return LAZY { \& my ($text) = @_; \& md5($text); \& } \& } .Ve .SS "Active contextual return values" .IX Subsection "Active contextual return values" Once a return value has been lazily evaluated in a given context, the resulting value is cached, and thereafter reused in that same context. .PP However, you can specify that, rather than being cached, the value should be re-evaluated \fIevery\fR time the value is used: .PP .Vb 6 \& sub make_counter { \& my $counter = 0; \& return ACTIVE \& SCALAR { ++$counter } \& ARRAYREF { [1..$counter] } \& } \& \& my $idx = make_counter(); \& \& print "$idx\en"; # 1 \& print "$idx\en"; # 2 \& print "[@$idx]\en"; # [1 2] \& print "$idx\en"; # 3 \& print "[@$idx]\en"; # [1 2 3] .Ve .SS "Semi-lazy contextual return values" .IX Subsection "Semi-lazy contextual return values" Sometimes, single or repeated lazy evaluation of a scalar return value in different contexts isn't what you really want. Sometimes what you really want is for the return value to be lazily evaluated once only (the first time it's used in any context), and then for that first value to be reused whenever the return value is subsequently reevaluated in any other context. .PP To get that behaviour, you can use the \f(CW\*(C`FIXED\*(C'\fR modifier, which causes the return value to morph itself into the actual value the first time it is used. For example: .PP .Vb 6 \& sub lazy { \& return \& SCALAR { 42 } \& ARRAYREF { [ 1, 2, 3 ] } \& ; \& } \& \& my $lazy = lazy(); \& print $lazy + 1; # 43 \& print "@{$lazy}"; # 1 2 3 \& \& \& sub semilazy { \& return FIXED \& SCALAR { 42 } \& ARRAYREF { [ 1, 2, 3 ] } \& ; \& } \& \& my $semi = semilazy(); \& print $semi + 1; # 43 \& print "@{$semi}"; # die q{Can\*(Aqt use string ("42") as an ARRAY ref} .Ve .SS "Finer distinctions of scalar context" .IX Subsection "Finer distinctions of scalar context" Because the scalar values returned from a context sequence are lazily evaluated, it becomes possible to be more specific about \fIwhat kind\fR of scalar value should be returned: a boolean, a number, or a string. To support those distinctions, Contextual::Return provides four extra context blocks: \&\f(CW\*(C`NUM\*(C'\fR, \f(CW\*(C`STR\*(C'\fR, \f(CW\*(C`BOOL\*(C'\fR, and \f(CW\*(C`PUREBOOL\*(C'\fR: .PP .Vb 2 \& 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... \& return ( \& LIST { @server_data{ qw(name uptime load users) } } \& PUREBOOL { $_ = $server_data{uptime}; $server_data{uptime} > 0 } \& BOOL { $server_data{uptime} > 0 } \& NUM { $server_data{load} } \& STR { "$server_data{name}: $server_data{uptime}" } \& VOID { print "$server_data{load}\en" } \& DEFAULT { croak q{Bad context! No biscuit!} } \& ); \& } .Ve .PP With these in place, the object returned from a scalar-context call to \&\f(CW\*(C`get_server_status()\*(C'\fR now behaves differently, depending on how it's used. For example: .PP .Vb 4 \& if ( my $status = get_server_status() ) { # BOOL: True if uptime > 0 \& $load_distribution[$status]++; # INT: Evaluates to load value \& print "$status\en"; # STR: Prints "name: uptime" \& } \& \& if (get_server_status()) { # PUREBOOL: also sets $_; \& print; # ...which is then used here \& } .Ve .PP \fIBoolean vs Pure Boolean contexts\fR .IX Subsection "Boolean vs Pure Boolean contexts" .PP There is a special subset of boolean contexts where the return value is being used and immediately thrown away. For example, in the loop: .PP .Vb 3 \& while (get_data()) { \& ... \& } .Ve .PP the value returned by \f(CW\*(C`get_data()\*(C'\fR is tested for truth and then discarded. This is known as \*(L"pure boolean context\*(R". In contrast, in the loop: .PP .Vb 3 \& while (my $data = get_data()) { \& ... \& } .Ve .PP the value returned by \f(CW\*(C`get_data()\*(C'\fR is first assigned to \f(CW$data\fR, then tested for truth. Because of the assignment, the return value is \fInot\fR discarded after the boolean test. This is ordinary \*(L"boolean context\*(R". .PP In Perl, pure boolean context is often associated with a special side-effect, that does not occur in regular boolean contexts. For example: .PP .Vb 1 \& while (<>) {...} # $_ set as side\-effect of pure boolean context \& \& while ($v = <>) {...} # $_ NOT set in ordinary boolean context .Ve .PP Contextual::Return supports this with a special subcase of \f(CW\*(C`BOOL\*(C'\fR named <\s-1PUREBOOL\s0>. In pure boolean contexts, Contextual::Return will call a \&\f(CW\*(C`PUREBOOL\*(C'\fR handler if one has been defined, or fall back to a \f(CW\*(C`BOOL\*(C'\fR or \f(CW\*(C`SCALAR\*(C'\fR handler if no \f(CW\*(C`PUREBOOL\*(C'\fR handler exists. In ordinary boolean contexts only the \f(CW\*(C`BOOL\*(C'\fR or \f(CW\*(C`SCALAR\*(C'\fR handlers are tried, even if a \f(CW\*(C`PUREBOOL\*(C'\fR handler is also defined. .PP Typically \f(CW\*(C`PUREBOOL\*(C'\fR handlers are set up to have some side-effect (most commonly: setting \f(CW$_\fR or <$@>), like so: .PP .Vb 2 \& sub get_data { \& my ($succeeded, @data) = _go_and_get_data(); \& \& return \& PUREBOOL { $_ = $data[0]; $succeeded; } \& BOOL { $succeeded; } \& SCALAR { $data[0]; } \& LIST { @data; } \& } .Ve .PP However, there is no requirement that they have side-effects. For example, they can also be used to implement \*(L"look-but-don't-retrieve-yet\*(R" checking: .PP .Vb 7 \& sub get_data { \& my $data; \& return \& PUREBOOL { _check_for_but_dont_get_data(); } \& BOOL { defined( $data ||= _go_and_get_data() ); } \& REF { $data ||= _go_and_get_data(); } \& } .Ve .SS "Self-reference within handlers" .IX Subsection "Self-reference within handlers" Any handler can refer to the contextual return object it is part of, by calling the \f(CW\*(C`RETOBJ()\*(C'\fR function. This is particularly useful for \f(CW\*(C`PUREBOOL\*(C'\fR and \f(CW\*(C`LIST\*(C'\fR handlers. For example: .PP .Vb 4 \& return \& PUREBOOL { $_ = RETOBJ; next handler; } \& BOOL { !$failed; } \& DEFAULT { $data; }; .Ve .SS "Referential contexts" .IX Subsection "Referential contexts" The other major kind of scalar return value is a reference. Contextual::Return provides contextual return blocks that allow you to specify what to (lazily) return when the return value of a subroutine is used as a reference to a scalar (\f(CW\*(C`SCALARREF {...}\*(C'\fR), to an array (\f(CW\*(C`ARRAYREF {...}\*(C'\fR), to a hash (\f(CW\*(C`HASHREF {...}\*(C'\fR), to a subroutine (\f(CW\*(C`CODEREF {...}\*(C'\fR), or to a typeglob (\f(CW\*(C`GLOBREF {...}\*(C'\fR). .PP For example, the server status subroutine shown earlier could be extended to allow it to return a hash reference, thereby supporting \*(L"named return values\*(R": .PP .Vb 2 \& 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... \& return ( \& LIST { @server_data{ qw(name uptime load users) } } \& BOOL { $server_data{uptime} > 0 } \& NUM { $server_data{load} } \& STR { "$server_data{name}: $server_data{uptime}" } \& VOID { print "$server_data{load}\en" } \& HASHREF { return \e%server_data } \& DEFAULT { croak q{Bad context! No biscuit!} } \& ); \& } \& \& # and later... \& \& my $users = get_server_status\->{users}; \& \& \& # or, lazily... \& \& my $server = get_server_status(); \& \& print "$server\->{name} load = $server\->{load}\en"; .Ve .SS "Interpolative referential contexts" .IX Subsection "Interpolative referential contexts" The \f(CW\*(C`SCALARREF {...}\*(C'\fR and \f(CW\*(C`ARRAYREF {...}\*(C'\fR context blocks are especially useful when you need to interpolate a subroutine into strings. For example, if you have a subroutine like: .PP .Vb 6 \& sub get_todo_tasks { \& return ( \& SCALAR { scalar @todo_list } # How many? \& LIST { @todo_list } # What are they? \& ); \& } \& \& # and later... \& \& print "There are ", scalar(get_todo_tasks()), " tasks:\en", \& get_todo_tasks(); .Ve .PP then you could make it much easier to interpolate calls to that subroutine by adding: .PP .Vb 4 \& sub get_todo_tasks { \& return ( \& SCALAR { scalar @todo_list } # How many? \& LIST { @todo_list } # What are they? \& \& SCALARREF { \escalar @todo_list } # Ref to how many \& ARRAYREF { \e@todo_list } # Ref to them \& ); \& } \& \& # and then... \& \& print "There are ${get_todo_tasks()} tasks:\en@{get_todo_tasks()}"; .Ve .PP In fact, this behaviour is so useful that it's the default. If you don't provide an explicit \f(CW\*(C`SCALARREF {...}\*(C'\fR block, Contextual::Return automatically provides an implicit one that simply returns a reference to whatever would have been returned in scalar context. Likewise, if no \f(CW\*(C`ARRAYREF {...}\*(C'\fR block is specified, the module supplies one that returns the list-context return value wrapped up in an array reference. .PP So you could just write: .PP .Vb 6 \& sub get_todo_tasks { \& return ( \& SCALAR { scalar @todo_list } # How many? \& LIST { @todo_list } # What are they? \& ); \& } \& \& # and still do this... \& \& print "There are ${get_todo_tasks()} tasks:\en@{get_todo_tasks()}"; .Ve .SS "Fallback contexts" .IX Subsection "Fallback contexts" As the previous sections imply, the \f(CW\*(C`BOOL {...}\*(C'\fR, \f(CW\*(C`NUM {...}\*(C'\fR, \f(CW\*(C`STR {...}\*(C'\fR, and various \f(CW\*(C`*REF {...}\*(C'\fR blocks, are special cases of the general \f(CW\*(C`SCALAR {...}\*(C'\fR context block. If a subroutine is called in one of these specialized contexts but does not use the corresponding context block, then the more general \f(CW\*(C`SCALAR {...}\*(C'\fR block is used instead (if it has been specified). .PP So, for example: .PP .Vb 2 \& sub read_value_from { \& my ($fh) = @_; \& \& my $value = <$fh>; \& chomp $value; \& \& return ( \& BOOL { defined $value } \& SCALAR { $value } \& ); \& } .Ve .PP ensures that the \f(CW\*(C`read_value_from()\*(C'\fR subroutine returns true in boolean contexts if the read was successful. But, because no specific \f(CW\*(C`NUM {...}\*(C'\fR or \f(CW\*(C`STR {...}\*(C'\fR return behaviours were specified, the subroutine falls back on using its generic \f(CW\*(C`SCALAR {...}\*(C'\fR block in all other scalar contexts. .PP Another way to think about this behaviour is that the various kinds of scalar context blocks form a hierarchy: .PP .Vb 8 \& SCALAR \& ^ \& | \& |\-\-< BOOL \& | \& |\-\-< NUM \& | \& \`\-\-< STR .Ve .PP Contextual::Return uses this hierarchical relationship to choose the most specific context block available to handle any particular return context, working its way up the tree from the specific type it needs, to the more general type, if that's all that is available. .PP There are two slight complications to this picture. The first is that Perl treats strings and numbers as interconvertable so the diagram (and the Contextual::Return module) also has to allow these interconversions as a fallback strategy: .PP .Vb 9 \& SCALAR \& ^ \& | \& |\-\-< BOOL \& | \& |\-\-< NUM \& | : ^ \& | v : \& \`\-\-< STR .Ve .PP The dotted lines are meant to indicate that this intraconversion is secondary to the main hierarchical fallback. That is, in a numeric context, a \f(CW\*(C`STR {...}\*(C'\fR block will only be used if there is no \f(CW\*(C`NUM {...}\*(C'\fR block \fIand\fR no \&\f(CW\*(C`SCALAR {...}\*(C'\fR block. In other words, the generic context type is always used in preference to string<\->number conversion. .PP The second slight complication is that the above diagram only shows a small part of the complete hierarchy of contexts supported by Contextual::Return. The full fallback hierarchy (including dotted interconversions) is: .PP .Vb 10 \& DEFAULT \& ^ \& | \& |\-\-< VOID \& | \& \`\-\-< NONVOID \& ^ \& | \& |\-\-< VALUE <............... \& | ^ : \& | | : \& | |\-\-< SCALAR <.......:... \& | | ^ : \& | | | : \& | | |\-\-< BOOL : \& | | | ^ : \& | | | | : \& | | | PUREBOOL : \& | | | : \& | | |\-\-< NUM <..:. \& | | | : ^ : \& | | | v : : \& | | \`\-\-< STR <....:.. \& | | : \& | | :: \& | \`\-\-< LIST ................: : \& | : ^ : \& | : : : \& \`\-\-\- REF : : : \& ^ : : : \& | v : : \& |\-\-< ARRAYREF : \& | : \& |\-\-< SCALARREF .............: \& | \& |\-\-< HASHREF \& | \& |\-\-< CODEREF \& | \& |\-\-< GLOBREF \& | \& \`\-\-< OBJREF <....... METHOD \& ^ \& :........... BLESSED .Ve .PP As before, each dashed arrow represents a fallback relationship. That is, if the required context specifier isn't available, the arrows are followed until a more generic one is found. The dotted arrows again represent the interconversion of return values, which is attempted only after the normal hierarchical fallback fails. .PP For example, if a subroutine is called in a context that expects a scalar reference, but no \f(CW\*(C`SCALARREF {...}\*(C'\fR block is provided, then Contextual::Return tries the following blocks in order: .PP .Vb 7 \& REF {...} \& NONVOID {...} \& DEFAULT {...} \& STR {...} (automatically taking a reference to the result) \& NUM {...} (automatically taking a reference to the result) \& SCALAR {...} (automatically taking a reference to the result) \& VALUE {...} (automatically taking a reference to the result) .Ve .PP Likewise, in a list context, if there is no \f(CW\*(C`LIST {...}\*(C'\fR context block, the module tries: .PP .Vb 7 \& VALUE {...} \& NONVOID {...} \& DEFAULT {...} \& ARRAYREF {...} (automatically dereferencing the result) \& STR {...} (treating it as a list of one element) \& NUM {...} (treating it as a list of one element) \& SCALAR {...} (treating it as a list of one element) .Ve .PP The more generic context blocks are especially useful for intercepting unexpected and undesirable call contexts. For example, to turn \fIoff\fR the automatic scalar-ref and array-ref interpolative behaviour described in \*(L"Interpolative referential contexts\*(R", you could intercept \fIall\fR referential contexts using a generic \f(CW\*(C`REF {...}\*(C'\fR context block: .PP .Vb 4 \& sub get_todo_tasks { \& return ( \& SCALAR { scalar @todo_list } # How many? \& LIST { @todo_list } # What are they? \& \& REF { croak q{get_todo_task() can\*(Aqt be used as a reference} } \& ); \& } \& \& print \*(AqThere are \*(Aq, get_todo_tasks(), \*(Aq...\*(Aq; # Still okay \& print "There are ${get_todo_tasks()}..."; # Throws an exception .Ve .SS "Treating return values as objects" .IX Subsection "Treating return values as objects" Normally, when a return value is treated as an object (i.e. has a method called on it), Contextual::Return invokes any \f(CW\*(C`OBJREF\*(C'\fR handler that was specified in the contextual return list, and delegates the method call to the object returned by that handler. .PP However, you can also be more specific, by specifying a \f(CW\*(C`METHOD\*(C'\fR context handler in the contextual return list. The block of this handler is expected to return one or more method\-name/method\-handler pairs, like so: .PP .Vb 7 \& return \& METHOD { \& get_count => sub { my $n = shift; $data[$n]{count} }, \& get_items => sub { my $n = shift; $data[$n]{items} }, \& clear => sub { @data = (); }, \& reset => sub { @data = (); }, \& } .Ve .PP Then, whenever one of the specified methods is called on the return value, the corresponding subroutine will be called to implement it. .PP The method handlers must always be subroutine references, but the method-name specifiers may be strings (as in the previous example) or they may be specified generically, as either regexes or array references. Generic method names are used to call the same handler for two or more distinct method names. For example, the previous example could be simplified to: .PP .Vb 5 \& return \& METHOD { \& qr/get_(\ew+)/ => sub { my $n = shift; $data[$n]{$1} }, \& [\*(Aqclear\*(Aq,\*(Aqreset\*(Aq] => sub { @data = (); }, \& } .Ve .PP A method name specified by regex will invoke the corresponding handler for any method call request that the regex matches. A method name specified by array ref will invoke the corresponding handler if the method requested matches any of the elements of the array (which may themselves be strings or regexes). .PP When the method handler is invoked, the name of the method requested is passed to the handler in \f(CW$_\fR, and the method's argument list is passed (as usual) via \f(CW@_\fR. .PP Note that any methods not explicitly handled by the \f(CW\*(C`METHOD\*(C'\fR handlers will still be delegated to the object returned by the \f(CW\*(C`OBJREF\*(C'\fR handler (if it is also specified). .SS "Not treating return values as objects" .IX Subsection "Not treating return values as objects" The use of \f(CW\*(C`OBJREF\*(C'\fR and \f(CW\*(C`METHOD\*(C'\fR are slightly complicated by the fact that contextual return values are themselves objects. .PP For example, prior to version 0.4.4 of the module, if you passed a contextual return value to \f(CW\*(C`Scalar::Util::blessed()\*(C'\fR, it always returned a true value (namely, the string: 'Contextual::Return::Value'), even if the return value had not specified handlers for \f(CW\*(C`OBJREF\*(C'\fR or \&\f(CW\*(C`METHOD\*(C'\fR. .PP In other words, the \fIimplementation\fR of contextual return values (as objects) was getting in the way of the \fIuse\fR of contextual return values (as non-objects). .PP So the module now also provides a \f(CW\*(C`BLESSED\*(C'\fR handler, which allows you to explicitly control how contextual return values interact with \&\f(CW\*(C`Scalar::Util::blessed()\*(C'\fR. .PP If \f(CW$crv\fR is a contextual return value, by default \&\f(CW\*(C`Scalar::Util::blessed($crv)\*(C'\fR will now only return true if that return value has a \f(CW\*(C`OBJREF\*(C'\fR, \f(CW\*(C`LAZY\*(C'\fR, \f(CW\*(C`REF\*(C'\fR, \f(CW\*(C`SCALAR\*(C'\fR, \f(CW\*(C`VALUE\*(C'\fR, \f(CW\*(C`NONVOID\*(C'\fR, or \f(CW\*(C`DEFAULT\*(C'\fR handler that in turn returns a blessed object. .PP However if \f(CW$crv\fR also provides a \f(CW\*(C`BLESSED\*(C'\fR handler, \f(CW\*(C`blessed()\*(C'\fR will return whatever that handler returns. .PP This means: .PP .Vb 4 \& sub simulate_non_object { \& return BOOL { 1 } \& NUM { 42 } \& } \& \& sub simulate_real_object { \& return OBJREF { bless {}, \*(AqMy::Class\*(Aq } \& BOOL { 1 } \& NUM { 42 } \& } \& \& sub simulate_faked_object { \& return BLESSED { \*(AqFoo\*(Aq } \& BOOL { 1 } \& NUM { 42 } \& } \& \& sub simulate_previous_behaviour { \& return BLESSED { \*(AqContextual::Return::Value\*(Aq } \& BOOL { 1 } \& NUM { 42 } \& } \& \& \& say blessed( simulate_non_object() ); # undef \& say blessed( simulate_real_object() ); # My::Class \& say blessed( simulate_faked_object() ); # Foo \& say blessed( simulate_previous_behaviour() ); # Contextual::Return::Value .Ve .PP Typically, you either want no \f(CW\*(C`BLESSED\*(C'\fR handler (in which case contextual return values pretend not to be blessed objects), or you want \&\f(CW\*(C`BLESSED { \*(AqContextual::Return::Value\*(Aq }\*(C'\fR for backwards compatibility with pre\-v0.4.7 behaviour. .PP \fIPreventing fallbacks\fR .IX Subsection "Preventing fallbacks" .PP Sometimes fallbacks can be too helpful. Or sometimes you want to impose strict type checking on a return value. .PP Contextual::Returns allows that via the \f(CW\*(C`STRICT\*(C'\fR specifier. If you include \&\f(CW\*(C`STRICT\*(C'\fR anywhere in your return statement, the module disables all fallbacks and will therefore through an exception if the return value is used in any way not explicitly specified in the contextual return sequence. .PP For example, to create a subroutine that returns only a string: .PP .Vb 3 \& sub get_name { \& return STRICT STR { \*(AqBruce\*(Aq } \& } .Ve .PP If the return value of the subroutine is used in any other way than as a string, an exception will be thrown. .PP You can still specify handlers for more than a single kind of context when using \f(CW\*(C`STRICT\*(C'\fR: .PP .Vb 5 \& sub get_name { \& return STRICT \& STR { \*(AqBruce\*(Aq } \& BOOL { 0 } \& } .Ve .PP \&...but these will still be the only contexts in which the return value can be used: .PP .Vb 1 \& my $n = get_name() ? 1 : 2; # Okay because BOOL handler specified \& \& my $n = \*(AqDr\*(Aq . get_name(); # Okay because STR handler specified \& \& my $n = 1 + get_name(); # Exception thrown because no NUM handler .Ve .PP In other words, \f(CW\*(C`STRICT\*(C'\fR allows you to impose strict type checking on your contextual return value. .SS "Deferring handlers" .IX Subsection "Deferring handlers" Because the various handlers form a hierarchy, it's possible to implement more specific handlers by falling back on (\*(L"deferring to\*(R") more general ones. For example, a \f(CW\*(C`PUREBOOL\*(C'\fR handler is almost always identical in its basic behaviour to the corresponding \f(CW\*(C`BOOL\*(C'\fR handler, except that it adds some side-effect. For example: .PP .Vb 4 \& return \& PUREBOOL { $_ = $return_val; defined $return_val && $return_val > 0 } \& BOOL { defined $return_val && $return_val > 0 } \& SCALAR { $return_val; } .Ve .PP So Contextual::Return allows you to have a handler perform some action and then defer to a more general handler to supply the actual return value. To fall back to a more general case in this way, you simply write: .PP .Vb 1 \& next handler; .Ve .PP at the end of the handler in question, after which Contextual::Return will find the next-most-specific handler and execute it as well. So the previous example, could be re-written: .PP .Vb 4 \& return \& PUREBOOL { $_ = $return_val; next handler; } \& BOOL { defined $return_val && $return_val > 0 } \& SCALAR { $return_val; } .Ve .PP Note that \fIany\fR specific handler can defer to a more general one in this same way. For example, you could provide consistent and maintainable type-checking for a subroutine that returns references by providing \f(CW\*(C`ARRAYREF\*(C'\fR, \f(CW\*(C`HASHREF\*(C'\fR, and \f(CW\*(C`SCALARREF\*(C'\fR handlers that all defer to a generic \f(CW\*(C`REF\*(C'\fR handler, like so: .PP .Vb 1 \& my $retval = _get_ref(); \& \& return \& SCALARREF { croak \*(AqType mismatch\*(Aq if ref($retval) ne \*(AqSCALAR\*(Aq; \& next handler; \& } \& ARRAYREF { croak \*(AqType mismatch\*(Aq if ref($retval) ne \*(AqARRAY\*(Aq; \& next handler; \& } \& HASHREF { croak \*(AqType mismatch\*(Aq if ref($retval) ne \*(AqHASH\*(Aq; \& next handler; \& } \& REF { $retval } .Ve .PP If, at a later time, the process of returning a reference became more complex, only the \f(CW\*(C`REF\*(C'\fR handler would have to be updated. .SS "Nested handlers" .IX Subsection "Nested handlers" Another way of factoring out return behaviour is to nest more specific handlers inside more general ones. For instance, in the final example given in \&\*(L"Boolean vs Pure Boolean contexts\*(R": .PP .Vb 7 \& sub get_data { \& my $data; \& return \& PUREBOOL { _check_for_but_dont_get_data(); } \& BOOL { defined( $data ||= _go_and_get_data() ); } \& REF { $data ||= _go_and_get_data(); } \& } .Ve .PP you could factor out the repeated calls to \f(CW\*(C`_go_and_get_data()\*(C'\fR like so: .PP .Vb 5 \& sub get_data { \& return \& PUREBOOL { _check_for_but_dont_get_data(); } \& DEFAULT { \& my $data = _go_and_get_data(); \& \& BOOL { defined $data; } \& REF { $data; } \& } \& } .Ve .PP Here, the \f(CW\*(C`DEFAULT\*(C'\fR handler deals with every return context except pure boolean. Within that \f(CW\*(C`DEFAULT\*(C'\fR handler, the data is first retrieved, and then two \*(L"sub-handlers\*(R" deal with the ordinary boolean and referential contexts. .PP Typically nested handlers are used in precisely this way: to optimize for inexpensive special cases (such as pure boolean or integer or void return contexts) and only do extra work for those other cases that require it. .SS "Failure contexts" .IX Subsection "Failure contexts" Two of the most common ways to specify that a subroutine has failed are to return a false value, or to throw an exception. The Contextual::Return module provides a mechanism that allows the subroutine writer to support \fIboth\fR of these mechanisms at the same time, by using the \f(CW\*(C`FAIL\*(C'\fR specifier. .PP A return statement of the form: .PP .Vb 1 \& return FAIL; .Ve .PP causes the surrounding subroutine to return \f(CW\*(C`undef\*(C'\fR (i.e. false) in boolean contexts, and to throw an exception in any other context. For example: .PP .Vb 1 \& use Contextual::Return; \& \& sub get_next_val { \& my $next_val = <>; \& return FAIL if !defined $next_val; \& chomp $next_val; \& return $next_val; \& } .Ve .PP If the \f(CW\*(C`return FAIL\*(C'\fR statement is executed, it will either return false in a boolean context: .PP .Vb 3 \& if (my $val = get_next_val()) { # returns undef if no next val \& print "[$val]\en"; \& } .Ve .PP or else throw an exception if the return value is used in any other context: .PP .Vb 1 \& print get_next_val(); # throws exception if no next val \& \& my $next_val = get_next_val(); \& print "[$next_val]\en"; # throws exception if no next val .Ve .PP The exception that is thrown is of the form: .PP .Vb 1 \& Call to main::get_next_val() failed at demo.pl line 42 .Ve .PP but you can change that message by providing a block to the \f(CW\*(C`FAIL\*(C'\fR, like so: .PP .Vb 1 \& return FAIL { "No more data" } if !defined $next_val; .Ve .PP in which case, the final value of the block becomes the exception message: .PP .Vb 1 \& No more data at demo.pl line 42 .Ve .PP A failure value can be interrogated for its error message, by calling its \&\f(CW\*(C`error()\*(C'\fR method, like so: .PP .Vb 7 \& my $val = get_next_val(); \& if ($val) { \& print "[$val]\en"; \& } \& else { \& print $val\->error, "\en"; \& } .Ve .SS "Configurable failure contexts" .IX Subsection "Configurable failure contexts" The default \f(CW\*(C`FAIL\*(C'\fR behaviour\*(--false in boolean context, fatal in all others\*(--works well in most situations, but violates the Platinum Rule ("Do unto others as \fIthey\fR would have done unto them"). .PP So it may be user-friendlier if the user of a module is allowed decide how the module's subroutines should behave on failure. For example, one user might prefer that failing subs always return undef; another might prefer that they always throw an exception; a third might prefer that they always log the problem and return a special Failure object; whilst a fourth user might want to get back \f(CW0\fR in scalar contexts, an empty list in list contexts, and an exception everywhere else. .PP You could create a module that allows the user to specify all these alternatives, like so: .PP .Vb 3 \& package MyModule; \& use Contextual::Return; \& use Log::StdLog; \& \& sub import { \& my ($package, @args) = @_; \& \& Contextual::Return::FAIL_WITH { \& \*(Aq:false\*(Aq => sub { return undef }, \& \*(Aq:fatal\*(Aq => sub { croak @_ }, \& \*(Aq:filed\*(Aq => sub { \& print STDLOG \*(AqSub \*(Aq, (caller 1)[3], \*(Aq failed\*(Aq; \& return Failure\->new(); \& }, \& \*(Aq:fussy\*(Aq => sub { \& SCALAR { undef } \& LIST { () } \& DEFAULT { croak @_ } \& }, \& }, @args; \& } .Ve .PP This configures Contextual::Return so that, instead of the usual false-or-fatal semantics, every \f(CW\*(C`return FAIL\*(C'\fR within MyModule's namespace is implemented by one of the four subroutines specified in the hash that was passed to \f(CW\*(C`FAIL_WITH\*(C'\fR. .PP Which of those four subs implements the \f(CW\*(C`FAIL\*(C'\fR is determined by the arguments passed after the hash (i.e. by the contents of \f(CW@args\fR). \&\f(CW\*(C`FAIL_WITH\*(C'\fR walks through that list of arguments and compares them against the keys of the hash. If a key matches an argument, the corresponding value is used as the implementation of \f(CW\*(C`FAIL\*(C'\fR. Note that, if subsequent arguments also match a key, their subroutine overrides the previously installed implementation, so only the final override has any effect. Contextual::Return generates warnings when multiple overrides are specified. .PP All of which mean that, if a user loaded the MyModule module like this: .PP .Vb 1 \& use MyModule qw( :fatal other args here ); .Ve .PP then every \f(CW\*(C`FAIL\*(C'\fR within MyModule would be reconfigured to throw an exception in all circumstances, since the presence of the \f(CW\*(Aq:fatal\*(Aq\fR in the argument list will cause \f(CW\*(C`FAIL_WITH\*(C'\fR to select the hash entry whose key is \f(CW\*(Aq:fatal\*(Aq\fR. .PP On the other hand, if they loaded the module: .PP .Vb 1 \& use MyModule qw( :fussy other args here ); .Ve .PP then each \f(CW\*(C`FAIL\*(C'\fR within MyModule would return undef or empty list or throw an exception, depending on context, since that's what the subroutine whose key is \&\f(CW\*(Aq:fussy\*(Aq\fR does. .PP Many people prefer module interfaces with a \f(CW\*(C`\f(CIflag\f(CW => \f(CIvalue\f(CW\*(C'\fR format, and \f(CW\*(C`FAIL_WITH\*(C'\fR supports this too. For example, if you wanted your module to take a \f(CW\*(C`\-fail\*(C'\fR flag, whose associated value could be any of \f(CW"undefined"\fR, \f(CW"exception"\fR, \f(CW"logged"\fR, or \f(CW"context"\fR, then you could implement that simply by specifying the flag as the first argument (i.e. \fIbefore\fR the hash) like so: .PP .Vb 2 \& sub import { \& my $package = shift; \& \& Contextual::Return::FAIL_WITH \-fail => { \& \*(Aqundefined\*(Aq => sub { return undef }, \& \*(Aqexception\*(Aq => sub { croak @_ }, \& \*(Aqlogged\*(Aq => sub { \& print STDLOG \*(AqSub \*(Aq, (caller 1)[3], \*(Aq failed\*(Aq; \& return Failure\->new(); \& }, \& \*(Aqcontext\*(Aq => sub { \& SCALAR { undef } \& LIST { () } \& DEFAULT { croak @_ } \& }, \& }, @_; .Ve .PP and then load the module: .PP .Vb 1 \& use MyModule qw( other args here ), \-fail=>\*(Aqundefined\*(Aq; .Ve .PP or: .PP .Vb 1 \& use MyModule qw( other args here ), \-fail=>\*(Aqexception\*(Aq; .Ve .PP In this case, \f(CW\*(C`FAIL_WITH\*(C'\fR scans the argument list for a pair of values: its flag string, followed by some other selector value. Then it looks up the selector value in the hash, and installs the corresponding subroutine as its local \f(CW\*(C`FAIL\*(C'\fR handler. .PP If this \*(L"flagged\*(R" interface is used, the user of the module can also specify their own handler directly, by passing a subroutine reference as the selector value instead of a string: .PP .Vb 1 \& use MyModule qw( other args here ), \-fail=>sub{ die \*(Aqhorribly\*(Aq}; .Ve .PP If this last example were used, any call to \f(CW\*(C`FAIL\*(C'\fR within MyModule would invoke the specified anonymous subroutine (and hence throw a \&'horribly' exception). .PP Note that, any overriding of a \f(CW\*(C`FAIL\*(C'\fR handler is specific to the namespace and file from which the subroutine that calls \f(CW\*(C`FAIL_WITH\*(C'\fR is itself called. Since \f(CW\*(C`FAIL_WITH\*(C'\fR is designed to be called from within a module's \f(CW\*(C`import()\*(C'\fR subroutine, that generally means that the \f(CW\*(C`FAIL\*(C'\fRs within a given module X are only overridden for the current namespace within the particular file from module X is loaded. This means that two separate pieces of code (in separate files or separate namespaces) can each independently override a module's \f(CW\*(C`FAIL\*(C'\fR behaviour, without interfering with each other. .SS "Lvalue contexts" .IX Subsection "Lvalue contexts" Recent versions of Perl offer (limited) support for lvalue subroutines: subroutines that return a modifiable variable, rather than a simple constant value. .PP Contextual::Return can make it easier to create such subroutines, within the limitations imposed by Perl itself. The limitations that Perl places on lvalue subs are: .IP "1." 4 The subroutine must be declared with an \f(CW\*(C`:lvalue\*(C'\fR attribute: .Sp .Vb 1 \& sub foo :lvalue {...} .Ve .IP "2." 4 The subroutine must not return via an explicit \f(CW\*(C`return\*(C'\fR. Instead, the last statement must evaluate to a variable, or must be a call to another lvalue subroutine call. .Sp .Vb 1 \& my ($foo, $baz); \& \& sub foo :lvalue { \& $foo; # last statement evals to a var \& } \& \& sub bar :lvalue { \& foo(); # last statement is lvalue sub call \& } \& \& sub baz :lvalue { \& my ($arg) = @_; \& \& $arg > 0 # last statement evals... \& ? $baz # ...to a var \& : bar(); # ...or to an lvalue sub call \& } .Ve .PP Thereafter, any call to the lvalue subroutine produces a result that can be assigned to: .PP .Vb 1 \& baz(0) = 42; # same as: $baz = 42 \& \& baz(1) = 84; # same as: bar() = 84 \& # which is the same as: foo() = 84 \& # which is the same as: $foo = 84 .Ve .PP Ultimately, every lvalue subroutine must return a scalar variable, which is then used as the lvalue of the assignment (or whatever other lvalue operation is applied to the subroutine call). Unfortunately, because the subroutine has to return this variable \fIbefore\fR the assignment can take place, there is no way that a normal lvalue subroutine can get access to the value that will eventually be assigned to its return value. .PP This is occasionally annoying, so the Contextual::Return module offers a solution: in addition to all the context blocks described above, it provides three special contextual return blocks specifically for use in lvalue subroutines: \f(CW\*(C`LVALUE\*(C'\fR, \f(CW\*(C`RVALUE\*(C'\fR, and \f(CW\*(C`NVALUE\*(C'\fR. .PP Using these blocks you can specify what happens when an lvalue subroutine is used in lvalue and non-lvalue (rvalue) context. For example: .PP .Vb 1 \& my $verbosity_level = 1; \& \& # Verbosity values must be between 0 and 5... \& sub verbosity :lvalue { \& LVALUE { $verbosity_level = max(0, min($_, 5)) } \& RVALUE { $verbosity_level } \& } .Ve .PP The \f(CW\*(C`LVALUE\*(C'\fR block is executed whenever \f(CW\*(C`verbosity\*(C'\fR is called as an lvalue: .PP .Vb 1 \& verbosity() = 7; .Ve .PP The block has access to the value being assigned, which is passed to it as \f(CW$_\fR. So, in the above example, the assigned value of 7 would be aliased to \f(CW$_\fR within the \f(CW\*(C`LVALUE\*(C'\fR block, would be reduced to 5 by the \&\*(L"min-of-max\*(R" expression, and then assigned to \f(CW$verbosity_level\fR. .PP (If you need to access the caller's \f(CW$_\fR, it's also still available: as \f(CW$CALLER::_\fR.) .PP When the subroutine isn't used as an lvalue: .PP .Vb 1 \& print verbosity(); .Ve .PP the \f(CW\*(C`RVALUE\*(C'\fR block is executed instead and its final value returned. Within an \f(CW\*(C`RVALUE\*(C'\fR block you can use any of the other features of Contextual::Return. For example: .PP .Vb 8 \& sub verbosity :lvalue { \& LVALUE { $verbosity_level = int max(0, min($_, 5)) } \& RVALUE { \& NUM { $verbosity_level } \& STR { $description[$verbosity_level] } \& BOOL { $verbosity_level > 2 } \& } \& } .Ve .PP but the context sequence must be nested inside an \f(CW\*(C`RVALUE\*(C'\fR block. .PP You can also specify what an lvalue subroutine should do when it is used neither as an lvalue nor as an rvalue (i.e. in void context), by using an \&\f(CW\*(C`NVALUE\*(C'\fR block: .PP .Vb 2 \& sub verbosity :lvalue { \& my ($level) = @_; \& \& NVALUE { $verbosity_level = int max(0, min($level, 5)) } \& LVALUE { $verbosity_level = int max(0, min($_, 5)) } \& RVALUE { \& NUM { $verbosity_level } \& STR { $description[$verbosity_level] } \& BOOL { $verbosity_level > 2 } \& } \& } .Ve .PP In this example, a call to \f(CW\*(C`verbosity()\*(C'\fR in void context sets the verbosity level to whatever argument is passed to the subroutine: .PP .Vb 1 \& verbosity(1); .Ve .PP Note that you \fIcannot\fR get the same effect by nesting a \f(CW\*(C`VOID\*(C'\fR block within an \f(CW\*(C`RVALUE\*(C'\fR block: .PP .Vb 7 \& LVALUE { $verbosity_level = int max(0, min($_, 5)) } \& RVALUE { \& NUM { $verbosity_level } \& STR { $description[$verbosity_level] } \& BOOL { $verbosity_level > 2 } \& VOID { $verbosity_level = $level } # Wrong! \& } .Ve .PP That's because, in a void context the return value is never evaluated, so it is never treated as an rvalue, which means the \f(CW\*(C`RVALUE\*(C'\fR block never executes. .SS "Result blocks" .IX Subsection "Result blocks" Occasionally, it's convenient to calculate a return value \fIbefore\fR the end of a contextual return block. For example, you may need to clean up external resources involved in the calculation after it's complete. Typically, this requirement produces a slightly awkward code sequence like this: .PP .Vb 7 \& return \& VALUE { \& $db\->start_work(); \& my $result = $db\->retrieve_query($query); \& $db\->commit(); \& $result; \& } .Ve .PP Such code sequences become considerably more awkward when you want the return value to be context sensitive, in which case you have to write either: .PP .Vb 10 \& return \& LIST { \& $db\->start_work(); \& my @result = $db\->retrieve_query($query); \& $db\->commit(); \& @result; \& } \& SCALAR { \& $db\->start_work(); \& my $result = $db\->retrieve_query($query); \& $db\->commit(); \& $result; \& } .Ve .PP or, worse: .PP .Vb 8 \& return \& VALUE { \& $db\->start_work(); \& my $result = LIST ? [$db\->retrieve_query($query)] \& : $db\->retrieve_query($query); \& $db\->commit(); \& LIST ? @{$result} : $result; \& } .Ve .PP To avoid these infelicities, Contextual::Return provides a second way of setting the result of a context block; a way that doesn't require that the result be the last statement in the block: .PP .Vb 11 \& return \& LIST { \& $db\->start_work(); \& RESULT { $db\->retrieve_query($query) }; \& $db\->commit(); \& } \& SCALAR { \& $db\->start_work(); \& RESULT { $db\->retrieve_query($query) }; \& $db\->commit(); \& } .Ve .PP The presence of a \f(CW\*(C`RESULT\*(C'\fR block inside a contextual return block causes that block to return the value of the final statement of the \f(CW\*(C`RESULT\*(C'\fR block as the handler's return value, rather than returning the value of the handler's own final statement. In other words, the presence of a \f(CW\*(C`RESULT\*(C'\fR block overrides the normal return value of a context handler. .PP Better still, the \f(CW\*(C`RESULT\*(C'\fR block always evaluates its final statement in the same context as the surrounding \f(CW\*(C`return\*(C'\fR, so you can just write: .PP .Vb 6 \& return \& VALUE { \& $db\->start_work(); \& RESULT { $db\->retrieve_query($query) }; \& $db\->commit(); \& } .Ve .PP and the \f(CW\*(C`retrieve_query()\*(C'\fR method will be called in the appropriate context in all cases. .PP A \f(CW\*(C`RESULT\*(C'\fR block can appear anywhere inside any contextual return block, but may not be used outside a context block. That is, this is an error: .PP .Vb 9 \& if ($db\->closed) { \& RESULT { undef }; # Error: not in a context block \& } \& return \& VALUE { \& $db\->start_work(); \& RESULT { $db\->retrieve_query($query) }; \& $db\->commit(); \& } .Ve .SS "Post-handler clean-up" .IX Subsection "Post-handler clean-up" If a subroutine uses an external resource, it's often necessary to close or clean-up that resource after the subroutine ends...regardless of whether the subroutine exits normally or via an exception. .PP Typically, this is done by encapsulating the resource in a lexically scoped object whose destructor does the clean-up. However, if the clean-up doesn't involve deallocation of an object (as in the \f(CW\*(C`$db\->commit()\*(C'\fR example in the previous section), it can be annoying to have to create a class and allocate a container object, merely to mediate the clean-up. .PP To make it easier to manage such resources, Contextual::Return supplies a special labelled block: the \f(CW\*(C`RECOVER\*(C'\fR block. If a \f(CW\*(C`RECOVER\*(C'\fR block is specified as part of a contextual return sequence, that block is executed after any context handler, even if the context handler exits via an exception. .PP So, for example, you could implement a simple commit-or-revert policy like so: .PP .Vb 11 \& return \& LIST { $db\->retrieve_all($query) } \& SCALAR { $db\->retrieve_next($query) } \& RECOVER { \& if ($@) { \& $db\->revert(); \& } \& else { \& $db\->commit(); \& } \& } .Ve .PP The presence of a \f(CW\*(C`RECOVER\*(C'\fR block also intercepts all exceptions thrown in any other context block in the same contextual return sequence. Any such exception is passed into the \f(CW\*(C`RECOVER\*(C'\fR block in the usual manner: via the \f(CW$@\fR variable. The exception may be rethrown out of the \&\f(CW\*(C`RECOVER\*(C'\fR block by calling \f(CW\*(C`die\*(C'\fR: .PP .Vb 7 \& return \& LIST { $db\->retrieve_all($query) } \& DEFAULT { croak "Invalid call (not in list context)" } \& RECOVER { \& die $@ if $@; # Propagate any exception \& $db\->commit(); # Otherwise commit the changes \& } .Ve .PP A \f(CW\*(C`RECOVER\*(C'\fR block can also access or replace the returned value, by invoking a \f(CW\*(C`RESULT\*(C'\fR block. For example: .PP .Vb 9 \& return \& LIST { attempt_to_generate_list_for(@_) } \& SCALAR { attempt_to_generate_count_for(@_) } \& RECOVER { \& if ($@) { # On any exception... \& warn "Replacing return value. Previously: ", RESULT; \& RESULT { undef } # ...return undef \& } \& } .Ve .SS "Post-return clean-up" .IX Subsection "Post-return clean-up" Occasionally it's necessary to defer the clean-up of resources until after the return value has been used. Once again, this is usually done by returning an object with a suitable destructor. .PP Using Contextual::Return you can get the same effect, by providing a \&\f(CW\*(C`CLEANUP\*(C'\fR block in the contextual return sequence: .PP .Vb 4 \& return \& LIST { $db\->retrieve_all($query) } \& SCALAR { $db\->retrieve_next($query) } \& CLEANUP { $db\->commit() } .Ve .PP In this example, the \f(CW\*(C`commit\*(C'\fR method call is only performed after the return value has been used by the caller. Note that this is quite different from using a \f(CW\*(C`RECOVER\*(C'\fR block, which is called as the subroutine returns its value; a \f(CW\*(C`CLEANUP\*(C'\fR is called when the returned value is garbage collected. .PP A \f(CW\*(C`CLEANUP\*(C'\fR block is useful for controlling resources allocated to support an \&\f(CW\*(C`ACTIVE\*(C'\fR return value. For example: .PP .Vb 1 \& my %file; \& \& # Return an active value that is always the next line from a file... \& sub readline_from { \& my ($file_name) = @_; \& \& # Open the file, if not already open... \& if (!$file{$file_name}) { \& open $file{$file_name}{handle}, \*(Aq<\*(Aq, $file_name; \& } \& \& # Track how many active return values are using this file... \& $file{$file_name}{count}++; \& \& return ACTIVE \& # Evaluating the return value returns the next line... \& VALUE { readline $file{$file_name}{handle} } \& \& # Once the active value is finished with, clean up the filehandle... \& CLEANUP { \& delete $file{$file_name} \& if \-\-$file{$file_name}{count} == 0; \& } \& } .Ve .SS "Debugging contextual return values" .IX Subsection "Debugging contextual return values" Contextual return values are implemented as opaque objects (using the \&\*(L"inside-out\*(R" technique). This means that passing such values to Data::Dumper produces an uninformative output like: .PP .Vb 1 \& $VAR1 = bless( do{\e(my $o = undef)}, \*(AqContextual::Return::Value\*(Aq ); .Ve .PP So the module provides two methods that allow contextual return values to be correctly reported: either directly, or when dumped by Data::Dumper. .PP To dump a contextual return value directly, call the module's \f(CW\*(C`DUMP()\*(C'\fR method explicitly and print the result: .PP .Vb 1 \& print $crv\->Contextual::Return::DUMP(); .Ve .PP This produces an output something like: .PP .Vb 11 \& [ \& { FROM => \*(Aqmain::foo\*(Aq }, \& { NO_HANDLER => [ \*(AqVOID\*(Aq, \*(AqCODEREF\*(Aq, \*(AqHASHREF\*(Aq, \*(AqGLOBREF\*(Aq ] }, \& { FALLBACKS => [ \*(AqVALUE\*(Aq ] }, \& { LIST => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] }, \& { STR => \*(Aq<<>>\*(Aq }, \& { NUM => 42 }, \& { BOOL => \-1 }, \& { SCALARREF => \*(Aq<<>>\*(Aq }, \& { ARRAYREF => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] }, \& ]; .Ve .PP The \f(CW\*(C`FROM\*(C'\fR hash entry names the subroutine that produced the return value. The \f(CW\*(C`NO_HANDLER\*(C'\fR hash entry lists those contexts for which no handler was defined (and which would therefore normally produce \*(L"can't call\*(R" exceptions such as: \f(CW"Can\*(Aqt call main::foo in VOID context"\fR). The \f(CW\*(C`FALLBACKS\*(C'\fR hash entry lists any \*(L"generic\*(R" contexts such as \&\f(CW\*(C`VALUE\*(C'\fR, \f(CW\*(C`NONVOID\*(C'\fR, \f(CW\*(C`REF\*(C'\fR, \f(CW\*(C`DEFAULT\*(C'\fR, etc. that the contextual return value can also handle. After these, all the remaining hash entries are actual contexts in which the return value could successfully be evaluated, and the value it would produce in each of those contexts. .PP The Data::Dumper module also has a mechanism by which you can tell it how to produce a similar listing automatically whenever a contextual return value is passed to its \f(CW\*(C`Dumper\*(C'\fR method. Data::Dumper allows you to register a \*(L"freezer\*(R" method, that is called prior to dumping, and which can be used to adapt an opaque object to make it dumpable. Contextual::Return provides just such a method (\f(CW\*(C`Contextual::Return::FREEZE()\*(C'\fR) for you to register, like so: .PP .Vb 1 \& use Data::Dumper \*(AqDumper\*(Aq; \& \& local $Data::Dumper::Freezer = \*(AqContextual::Return::FREEZE\*(Aq; \& \& print Dumper $foo; .Ve .PP The output is then precisely the same as \f(CW\*(C`Contextual::Return::DUMP()\*(C'\fR would produce. .PP Note that, with both of the above dumping mechanisms, it is essential to use the full name of the method. That is: .PP .Vb 1 \& print $crv\->Contextual::Return::DUMP(); .Ve .PP rather than: .PP .Vb 1 \& print $crv\->DUMP(); .Ve .PP This is because the shorter version is interpreted as calling the \&\f(CW\*(C`DUMP()\*(C'\fR method on the object returned by the return value's \f(CW\*(C`OBJREF\*(C'\fR context block (see \*(L"Scalar reference contexts\*(R") .PP For the same reason, you must write: .PP .Vb 1 \& local $Data::Dumper::Freezer = \*(AqContextual::Return::FREEZE\*(Aq; .Ve .PP not: .PP .Vb 1 \& local $Data::Dumper::Freezer = \*(AqFREEZE\*(Aq; .Ve .SS "Namespace controls" .IX Subsection "Namespace controls" By default the module exports a large number of return context markers: .PP .Vb 10 \& DEFAULT REF LAZY \& VOID SCALARREF FIXED \& NONVOID ARRAYREF ACTIVE \& LIST CODEREF RESULT \& SCALAR HASHREF RECOVER \& VALUE GLOBREF CLEANUP \& STR OBJREF RVALUE \& NUM METHOD LVALUE \& BOOL NVALUE \& PUREBOOL .Ve .PP These are exported as subroutines, and so can conflict with existing subroutines in your namespace, or with subroutines imported from other modules. .PP Contextual::Return allows you to control which contextual return blocks are exported into any namespace that uses the module. It also allows you to rename blocks to avoid namespace conflicts with existing subroutines. .PP Both these features are controlled by passing arguments to the \f(CW\*(C`use\*(C'\fR statement that loads the module as follows: .IP "\(bu" 4 Any string passed as an argument to \f(CW\*(C`use Contextual::Return\*(C'\fR, exports only the block name it specifies; .IP "\(bu" 4 Any regex passed as an argument to \f(CW\*(C`use Contextual::Return\*(C'\fR exports every block name it matches; .IP "\(bu" 4 Any array ref (recursively) exports each of its elements .IP "\(bu" 4 Any string that appears immediately after one of the above three specifiers, and which is not itself a block name, renames the handlers exported by that preceding specifier by filtering each handler name through \f(CW\*(C`sprintf()\*(C'\fR .PP That is, you can specify handlers to be exported by exact name (as a string), by general pattern (as a regex), or collectively (in an array). And after any of these export specifications, you can append a template in which any \f(CW\*(Aq%s\*(Aq\fR will be replaced by the original name of the handler. For example: .PP .Vb 3 \& # Selectively export specific sets of handlers... \& use Contextual::Return qr/[NLR]VALUE/; \& use Contextual::Return qr/.*REF/; \& \& # Selective export specific sets and add a suffix to each... \& use Contextual::Return qr/[NLR]VALUE/ => \*(Aq%s_CONTEXT\*(Aq; \& \& # Selective export specific sets and add a prefix to each... \& use Contextual::Return qr/.*REF/ => \*(AqCR_%s\*(Aq; \& \& # Export a list of handlers... \& use Contextual::Return \*(AqNUM\*(Aq, \*(AqSTR\*(Aq, \*(AqBOOL\*(Aq ; \& use Contextual::Return qw< NUM STR BOOL >; \& use Contextual::Return [\*(AqNUM\*(Aq, \*(AqSTR\*(Aq, \*(AqBOOL\*(Aq]; \& \& # Export a list of handlers, renaming them individually... \& use Contextual::Return NUM => \*(AqNUMERIC\*(Aq, STR => \*(AqTEXT\*(Aq, BOOL => \*(AqCR_%s\*(Aq; \& \& # Export a list of handlers, renaming them collectively... \& use Contextual::Return [\*(AqNUM\*(Aq, \*(AqSTR\*(Aq, \*(AqBOOL\*(Aq] => \*(Aq%s_CONTEXT\*(Aq; \& \& # Mixed exports and renames... \& use Contextual::Return ( \& STR => \*(AqTEXT\*(Aq, \& [\*(AqNUM\*(Aq, \*(AqBOOL\*(Aq] => \*(AqCR_%s\*(Aq, \& [\*(AqLIST\*(Aq, \*(AqSCALAR\*(Aq, \*(AqVOID\*(Aq, qr/^[NLR]VALUE/] => \*(Aq%s_CONTEXT\*(Aq, \& ); .Ve .SH "INTERFACE" .IX Header "INTERFACE" .SS "Context tests" .IX Subsection "Context tests" .ie n .IP """LIST()""" 4 .el .IP "\f(CWLIST()\fR" 4 .IX Item "LIST()" Returns true if the current subroutine was called in list context. A cleaner way of writing: \f(CW\*(C`wantarray()\*(C'\fR .ie n .IP """SCALAR()""" 4 .el .IP "\f(CWSCALAR()\fR" 4 .IX Item "SCALAR()" Returns true if the current subroutine was called in scalar context. A cleaner way of writing: \f(CW\*(C`defined wantarray() && ! wantarray()\*(C'\fR .ie n .IP """VOID()""" 4 .el .IP "\f(CWVOID()\fR" 4 .IX Item "VOID()" Returns true if the current subroutine was called in void context. A cleaner way of writing: \f(CW\*(C`!defined wantarray()\*(C'\fR .ie n .IP """NONVOID()""" 4 .el .IP "\f(CWNONVOID()\fR" 4 .IX Item "NONVOID()" Returns true if the current subroutine was called in list or scalar context. A cleaner way of writing: \f(CW\*(C`defined wantarray()\*(C'\fR .SS "Standard contexts" .IX Subsection "Standard contexts" .ie n .IP """LIST {...}""" 4 .el .IP "\f(CWLIST {...}\fR" 4 .IX Item "LIST {...}" The block specifies what the context sequence should evaluate to when called in list context. .ie n .IP """SCALAR {...}""" 4 .el .IP "\f(CWSCALAR {...}\fR" 4 .IX Item "SCALAR {...}" The block specifies what the context sequence should evaluate to in scalar contexts, unless some more-specific specifier scalar context specifier (see below) also occurs in the same context sequence. .ie n .IP """VOID {...}""" 4 .el .IP "\f(CWVOID {...}\fR" 4 .IX Item "VOID {...}" The block specifies what the context sequence should do when called in void context. .SS "Scalar value contexts" .IX Subsection "Scalar value contexts" .ie n .IP """BOOL {...}""" 4 .el .IP "\f(CWBOOL {...}\fR" 4 .IX Item "BOOL {...}" The block specifies what the context sequence should evaluate to when treated as a boolean value. .ie n .IP """NUM {...}""" 4 .el .IP "\f(CWNUM {...}\fR" 4 .IX Item "NUM {...}" The block specifies what the context sequence should evaluate to when treated as a numeric value. .ie n .IP """STR {...}""" 4 .el .IP "\f(CWSTR {...}\fR" 4 .IX Item "STR {...}" The block specifies what the context sequence should evaluate to when treated as a string value. .ie n .IP """LAZY {...}""" 4 .el .IP "\f(CWLAZY {...}\fR" 4 .IX Item "LAZY {...}" Another name for \f(CW\*(C`SCALAR {...}\*(C'\fR. Usefully self-documenting when the primary purpose of the contextual return is to defer evaluation of the return value until it's actually required. .SS "Scalar reference contexts" .IX Subsection "Scalar reference contexts" .ie n .IP """SCALARREF {...}""" 4 .el .IP "\f(CWSCALARREF {...}\fR" 4 .IX Item "SCALARREF {...}" The block specifies what the context sequence should evaluate to when treated as a reference to a scalar. .ie n .IP """ARRAYREF {...}""" 4 .el .IP "\f(CWARRAYREF {...}\fR" 4 .IX Item "ARRAYREF {...}" The block specifies what the context sequence should evaluate to when treated as a reference to an array. .ie n .IP """HASHREF {...}""" 4 .el .IP "\f(CWHASHREF {...}\fR" 4 .IX Item "HASHREF {...}" The block specifies what the context sequence should evaluate to when treated as a reference to a hash. .Sp Note that a common error here is to write: .Sp \&\s-1HASHREF\s0 { a=>1, b=>2, c=>3 } .Sp The curly braces there are a block, not a hash constructor, so the block doesn't return a hash reference and the interpreter throws an exception. What's needed is: .Sp \&\s-1HASHREF\s0 { {a=>1, b=>2, c=>3} } .Sp in which the inner braces \fIare\fR a hash constructor. .ie n .IP """CODEREF {...}""" 4 .el .IP "\f(CWCODEREF {...}\fR" 4 .IX Item "CODEREF {...}" The block specifies what the context sequence should evaluate to when treated as a reference to a subroutine. .ie n .IP """GLOBREF {...}""" 4 .el .IP "\f(CWGLOBREF {...}\fR" 4 .IX Item "GLOBREF {...}" The block specifies what the context sequence should evaluate to when treated as a reference to a typeglob. .ie n .IP """OBJREF {...}""" 4 .el .IP "\f(CWOBJREF {...}\fR" 4 .IX Item "OBJREF {...}" The block specifies what the context sequence should evaluate to when treated as a reference to an object. .ie n .IP """METHOD {...}""" 4 .el .IP "\f(CWMETHOD {...}\fR" 4 .IX Item "METHOD {...}" The block can be used to specify particular handlers for specific method calls when the return value is treated as an object reference. It should return a list of methodname/methodbody pairs. Each method name can be specified as a string, a regex, or an array of strings or regexes. The method bodies must be specified as subroutine references (usually anonymous subs). The first method name that matches the actual method call selects the corresponding handler, which is then called. .SS "Generic contexts" .IX Subsection "Generic contexts" .ie n .IP """VALUE {...}""" 4 .el .IP "\f(CWVALUE {...}\fR" 4 .IX Item "VALUE {...}" The block specifies what the context sequence should evaluate to when treated as a non-referential value (as a boolean, numeric, string, scalar, or list). Only used if there is no more-specific value context specifier in the context sequence. .ie n .IP """REF {...}""" 4 .el .IP "\f(CWREF {...}\fR" 4 .IX Item "REF {...}" The block specifies what the context sequence should evaluate to when treated as a reference of any kind. Only used if there is no more-specific referential context specifier in the context sequence. .ie n .IP """NONVOID {...}""" 4 .el .IP "\f(CWNONVOID {...}\fR" 4 .IX Item "NONVOID {...}" The block specifies what the context sequence should evaluate to when used in a non-void context of any kind. Only used if there is no more-specific context specifier in the context sequence. .ie n .IP """DEFAULT {...}""" 4 .el .IP "\f(CWDEFAULT {...}\fR" 4 .IX Item "DEFAULT {...}" The block specifies what the context sequence should evaluate to when used in a void or non-void context of any kind. Only used if there is no more-specific context specifier in the context sequence. .SS "Failure context" .IX Subsection "Failure context" .ie n .IP """FAIL""" 4 .el .IP "\f(CWFAIL\fR" 4 .IX Item "FAIL" This block is executed unconditionally and is used to indicate failure. In a Boolean context it return false. In all other contexts it throws an exception consisting of the final evaluated value of the block. .Sp That is, using \f(CW\*(C`FAIL\*(C'\fR: .Sp return \&\s-1FAIL\s0 { \*(L"Could not defenestrate the widget\*(R" } .Sp is exactly equivalent to writing: .Sp return \&\s-1BOOL\s0 { 0 } \&\s-1DEFAULT\s0 { croak \*(L"Could not defenestrate the widget\*(R" } .Sp except that the reporting of errors is a little smarter under \f(CW\*(C`FAIL\*(C'\fR. .Sp If \f(CW\*(C`FAIL\*(C'\fR is called without specifying a block: .Sp return \s-1FAIL\s0; .Sp it is equivalent to: .Sp return \s-1FAIL\s0 { croak \*(L"Call to failed\*(R" } .Sp (where \f(CW\*(C`\*(C'\fR is replaced with the name of the surrounding subroutine). .Sp Note that, because \f(CW\*(C`FAIL\*(C'\fR implicitly covers every possible return context, it cannot be chained with other context specifiers. .ie n .IP """Contextual::Return::FAIL_WITH""" 4 .el .IP "\f(CWContextual::Return::FAIL_WITH\fR" 4 .IX Item "Contextual::Return::FAIL_WITH" This subroutine is not exported, but may be called directly to reconfigure \&\f(CW\*(C`FAIL\*(C'\fR behaviour in the caller's namespace. .Sp The subroutine is called with an optional string (the \fIflag\fR), followed by a mandatory hash reference (the \fIconfigurations hash\fR), followed by a list of zero-or-more strings (the \fIselector list\fR). The values of the configurations hash must all be subroutine references. .Sp If the optional flag is specified, \f(CW\*(C`FAIL_WITH\*(C'\fR searches the selector list looking for that string, then uses the \fIfollowing\fR item in the selector list as its \fIselector value\fR. If that selector value is a string, \f(CW\*(C`FAIL_WITH\*(C'\fR looks up that key in the hash, and installs the corresponding subroutine as the namespace's \f(CW\*(C`FAIL\*(C'\fR handler (an exception is thrown if the selector string is not a valid key of the configurations hash). If the selector value is a subroutine reference, \&\f(CW\*(C`FAIL_WITH\*(C'\fR installs that subroutine as the \f(CW\*(C`FAIL\*(C'\fR handler. .Sp If the optional flag is \fInot\fR specified, \f(CW\*(C`FAIL_WITH\*(C'\fR searches the entire selector list looking for the last element that matches any key in the configurations hash. It then looks up that key in the hash, and installs the corresponding subroutine as the namespace's \&\f(CW\*(C`FAIL\*(C'\fR handler. .Sp See \*(L"Configurable failure contexts\*(R" for examples of using this feature. .SS "Lvalue contexts" .IX Subsection "Lvalue contexts" .ie n .IP """LVALUE""" 4 .el .IP "\f(CWLVALUE\fR" 4 .IX Item "LVALUE" This block is executed when the result of an \f(CW\*(C`:lvalue\*(C'\fR subroutine is assigned to. The assigned value is passed to the block as \f(CW$_\fR. To access the caller's \&\f(CW$_\fR value, use \f(CW$CALLER::_\fR. .ie n .IP """RVALUE""" 4 .el .IP "\f(CWRVALUE\fR" 4 .IX Item "RVALUE" This block is executed when the result of an \f(CW\*(C`:lvalue\*(C'\fR subroutine is used as an rvalue. The final value that is evaluated in the block becomes the rvalue. .ie n .IP """NVALUE""" 4 .el .IP "\f(CWNVALUE\fR" 4 .IX Item "NVALUE" This block is executed when an \f(CW\*(C`:lvalue\*(C'\fR subroutine is evaluated in void context. .SS "Explicit result blocks" .IX Subsection "Explicit result blocks" .ie n .IP """RESULT""" 4 .el .IP "\f(CWRESULT\fR" 4 .IX Item "RESULT" This block may only appear inside a context handler block. It causes the surrounding handler to return the final value of the \f(CW\*(C`RESULT\*(C'\fR's block, rather than the final value of the handler's own block. This override occurs regardless of the location to the \f(CW\*(C`RESULT\*(C'\fR block within the handler. .Sp If called without a trailing \f(CW\*(C`{...}\*(C'\fR, it simply returns the current result value in scalar contexts, or the list of result values in list context. .SS "Recovery blocks" .IX Subsection "Recovery blocks" .ie n .IP """RECOVER""" 4 .el .IP "\f(CWRECOVER\fR" 4 .IX Item "RECOVER" If present in a context return sequence, this block grabs control after any context handler returns or exits via an exception. If an exception was thrown it is passed to the \f(CW\*(C`RECOVER\*(C'\fR block via the \f(CW$@\fR variable. .SS "Clean-up blocks" .IX Subsection "Clean-up blocks" .ie n .IP """CLEANUP""" 4 .el .IP "\f(CWCLEANUP\fR" 4 .IX Item "CLEANUP" If present in a context return sequence, this block grabs control when a return value is garbage collected. .SS "Modifiers" .IX Subsection "Modifiers" .ie n .IP """FIXED""" 4 .el .IP "\f(CWFIXED\fR" 4 .IX Item "FIXED" This specifies that the scalar value will only be evaluated once, the first time it is used, and that the value will then morph into that evaluated value. .ie n .IP """ACTIVE""" 4 .el .IP "\f(CWACTIVE\fR" 4 .IX Item "ACTIVE" This specifies that the scalar value's originating block will be re\- evaluated every time the return value is used. .SS "Debugging support" .IX Subsection "Debugging support" .ie n .IP """$crv\->Contextual::Return::DUMP()""" 4 .el .IP "\f(CW$crv\->Contextual::Return::DUMP()\fR" 4 .IX Item "$crv->Contextual::Return::DUMP()" Return a dumpable representation of the return value in all viable contexts. .ie n .IP """local $Data::Dumper::Freezer = \*(AqContextual::Return::FREEZE\*(Aq;""" 4 .el .IP "\f(CWlocal $Data::Dumper::Freezer = \*(AqContextual::Return::FREEZE\*(Aq;\fR" 4 .IX Item "local $Data::Dumper::Freezer = Contextual::Return::FREEZE;" .PD 0 .ie n .IP """local $Data::Dumper::Freezer = \e&Contextual::Return::FREEZE;""" 4 .el .IP "\f(CWlocal $Data::Dumper::Freezer = \e&Contextual::Return::FREEZE;\fR" 4 .IX Item "local $Data::Dumper::Freezer = &Contextual::Return::FREEZE;" .PD Configure Data::Dumper to correctly dump a representation of the contextual return value. .SH "DIAGNOSTICS" .IX Header "DIAGNOSTICS" .ie n .IP """Can\*(Aqt use %s as export specifier""" 4 .el .IP "\f(CWCan\*(Aqt use %s as export specifier\fR" 4 .IX Item "Cant use %s as export specifier" In your \f(CW\*(C`use Contextual::Return\*(C'\fR statement you specified something (such as a hash or coderef) that can't be used to select what the module exports. Make sure the list of selectors includes only strings, regexes, or references to arrays of strings or regexes. .ie n .IP """use Contextual::Return qr{%s} didn\*(Aqt export anything""" 4 .el .IP "\f(CWuse Contextual::Return qr{%s} didn\*(Aqt export anything\fR" 4 .IX Item "use Contextual::Return qr{%s} didnt export anything" In your \f(CW\*(C`use Contextual::Return\*(C'\fR statement you specified a regex to select which handlers to support, but the regex didn't select any handlers. Check that the regex you're using actually does match at least one of the names of the modules many handlers. .ie n .IP """Can\*(Aqt export %s: no such handler""" 4 .el .IP "\f(CWCan\*(Aqt export %s: no such handler\fR" 4 .IX Item "Cant export %s: no such handler" In your \f(CW\*(C`use Contextual::Return\*(C'\fR statement you specified a string as the name of a context handler to be exported, but the module doesn't export a handler of that name. Check the spelling for the requested export. .ie n .IP """Can\*(Aqt call %s in a %s context""" 4 .el .IP "\f(CWCan\*(Aqt call %s in a %s context\fR" 4 .IX Item "Cant call %s in a %s context" .PD 0 .ie n .IP """Can\*(Aqt use return value of %s in a %s context""" 4 .el .IP "\f(CWCan\*(Aqt use return value of %s in a %s context\fR" 4 .IX Item "Cant use return value of %s in a %s context" .PD The subroutine you called uses a contextual return, but doesn't specify what to return in the particular context in which you called it. You either need to change the context in which you're calling the subroutine, or else add a context block corresponding to the offending context (or perhaps a \&\f(CW\*(C`DEFAULT {...}\*(C'\fR block). .ie n .IP """Can\*(Aqt call bare %s {...} in %s context""" 4 .el .IP "\f(CWCan\*(Aqt call bare %s {...} in %s context\fR" 4 .IX Item "Cant call bare %s {...} in %s context" You specified a handler (such as \f(CW\*(C`VOID {...}\*(C'\fR or \f(CW\*(C`LIST {...}\*(C'\fR) outside any subroutine, and in a context that it can't handle. Did you mean to place the handler outside of a subroutine? If so, then you need to put it in a context it can actually handle. Otherwise, perhaps you need to replace the trailing block with parens (that is: \f(CW\*(C`VOID()\*(C'\fR or \f(CW\*(C`LIST()\*(C'\fR). .ie n .IP """Call to %s at %s didn\*(Aqt return a %s reference""""" 4 .el .IP "\f(CWCall to %s at %s didn\*(Aqt return a %s reference""\fR" 4 .IX Item "Call to %s at %s didnt return a %s reference""" You called the subroutine in a context that expected to get back a reference of some kind but the subroutine didn't specify the corresponding \f(CW\*(C`SCALARREF\*(C'\fR, \f(CW\*(C`ARRAYREF\*(C'\fR, \f(CW\*(C`HASHREF\*(C'\fR, \f(CW\*(C`CODEREF\*(C'\fR, \&\f(CW\*(C`GLOBREF\*(C'\fR, or generic \f(CW\*(C`REF\*(C'\fR, \f(CW\*(C`NONVOID\*(C'\fR, or \f(CW\*(C`DEFAULT\*(C'\fR handlers. You need to specify the appropriate one of these handlers in the subroutine. .ie n .IP """Can\*(Aqt call method \*(Aq%s\*(Aq on %s value returned by %s""""" 4 .el .IP "\f(CWCan\*(Aqt call method \*(Aq%s\*(Aq on %s value returned by %s""\fR" 4 .IX Item "Cant call method %s on %s value returned by %s""" You called the subroutine and then tried to call a method on the return value, but the subroutine returned a classname or object that doesn't have that method. This probably means that the subroutine didn't return the classname or object you expected. Or perhaps you need to specify an \f(CW\*(C`OBJREF {...}\*(C'\fR context block. .ie n .IP """Can\*(Aqt install two %s handlers""" 4 .el .IP "\f(CWCan\*(Aqt install two %s handlers\fR" 4 .IX Item "Cant install two %s handlers" You attempted to specify two context blocks of the same name in the same return context, which is ambiguous. For example: .Sp .Vb 5 \& sub foo: lvalue { \& LVALUE { $foo = $_ } \& RVALUE { $foo } \& LVALUE { $foo = substr($_,1,10) } \& } .Ve .Sp or: .Sp .Vb 7 \& sub bar { \& return \& BOOL { 0 } \& NUM { 1 } \& STR { "two" } \& BOOL { 1 }; \& } .Ve .Sp Did you cut-and-paste wrongly, or mislabel one of the blocks? .ie n .IP """Expected a %s block after the %s block but found instead: %s""" 4 .el .IP "\f(CWExpected a %s block after the %s block but found instead: %s\fR" 4 .IX Item "Expected a %s block after the %s block but found instead: %s" If you specify any of \f(CW\*(C`LVALUE\*(C'\fR, \f(CW\*(C`RVALUE\*(C'\fR, or \f(CW\*(C`NVALUE\*(C'\fR, then you can only specify \f(CW\*(C`LVALUE\*(C'\fR, \f(CW\*(C`RVALUE\*(C'\fR, or \f(CW\*(C`NVALUE\*(C'\fR blocks in the same return context. If you need to specify other contexts (like \f(CW\*(C`BOOL\*(C'\fR, or \f(CW\*(C`STR\*(C'\fR, or \f(CW\*(C`REF\*(C'\fR, etc.), put them inside an \f(CW\*(C`RVALUE\*(C'\fR block. See \*(L"Lvalue contexts\*(R" for an example. .ie n .IP """Call to %s failed at %s""" 4 .el .IP "\f(CWCall to %s failed at %s\fR" 4 .IX Item "Call to %s failed at %s" This is the default exception that a \f(CW\*(C`FAIL\*(C'\fR throws in a non-scalar context. Which means that the subroutine you called has signalled failure by throwing an exception, and you didn't catch that exception. You should either put the call in an \f(CW\*(C`eval {...}\*(C'\fR block or else call the subroutine in boolean context instead. .ie n .IP """Call to %s failed at %s. Attempted to use failure value at %s""" 4 .el .IP "\f(CWCall to %s failed at %s. Attempted to use failure value at %s\fR" 4 .IX Item "Call to %s failed at %s. Attempted to use failure value at %s" This is the default exception that a \f(CW\*(C`FAIL\*(C'\fR throws when a failure value is captured in a scalar variable and later used in a non-boolean context. That means that the subroutine you called must have failed, and you didn't check the return value for that failure, so when you tried to use that invalid value it killed your program. You should either put the original call in an \f(CW\*(C`eval {...}\*(C'\fR or else test the return value in a boolean context and avoid using it if it's false. .ie n .IP """Usage: FAIL_WITH $flag_opt, \e%selector, @args""" 4 .el .IP "\f(CWUsage: FAIL_WITH $flag_opt, \e%selector, @args\fR" 4 .IX Item "Usage: FAIL_WITH $flag_opt, %selector, @args" The \f(CW\*(C`FAIL_WITH\*(C'\fR subroutine expects an optional flag, followed by a reference to a configuration hash, followed by a list or selector arguments. You gave it something else. See \*(L"Configurable Failure Contexts\*(R". .ie n .IP """Selector values must be sub refs""" 4 .el .IP "\f(CWSelector values must be sub refs\fR" 4 .IX Item "Selector values must be sub refs" You passed a configuration hash to \f(CW\*(C`FAIL_WITH\*(C'\fR that specified non\- subroutines as possible \f(CW\*(C`FAIL\*(C'\fR handlers. Since non-subroutines can't possibly be handlers, maybe you forgot the \f(CW\*(C`sub\*(C'\fR keyword somewhere? .ie n .IP """Invalid option: %s ="" %s>" 4 .el .IP "\f(CWInvalid option: %s =\fR \f(CW%s\fR>" 4 .IX Item "Invalid option: %s = %s>" The \f(CW\*(C`FAIL_WITH\*(C'\fR subroutine was passed a flag/selector pair, but the selector was not one of those allowed by the configuration hash. .ie n .IP """FAIL handler for package %s redefined""" 4 .el .IP "\f(CWFAIL handler for package %s redefined\fR" 4 .IX Item "FAIL handler for package %s redefined" A warning that the \f(CW\*(C`FAIL\*(C'\fR handler for a particular package was reconfigured more than once. Typically that's because the module was loaded in two places with difference configurations specified. You can't reasonably expect two different sets of behaviours from the one module within the one namespace. .SH "CONFIGURATION AND ENVIRONMENT" .IX Header "CONFIGURATION AND ENVIRONMENT" Contextual::Return requires no configuration files or environment variables. .SH "DEPENDENCIES" .IX Header "DEPENDENCIES" Requires version.pm and Want.pm. .SH "INCOMPATIBILITIES" .IX Header "INCOMPATIBILITIES" \&\f(CW\*(C`LVALUE\*(C'\fR, \f(CW\*(C`RVALUE\*(C'\fR, and \f(CW\*(C`NVALUE\*(C'\fR do not work correctly under the Perl debugger. This seems to be because the debugger injects code to capture the return values from subroutines, which interferes destructively with the optional final arguments that allow \f(CW\*(C`LVALUE\*(C'\fR, \f(CW\*(C`RVALUE\*(C'\fR, and \f(CW\*(C`NVALUE\*(C'\fR to cascade within a single return. .SH "BUGS AND LIMITATIONS" .IX Header "BUGS AND LIMITATIONS" No bugs have been reported. .SH "AUTHOR" .IX Header "AUTHOR" Damian Conway \f(CW\*(C`\*(C'\fR .SH "LICENCE AND COPYRIGHT" .IX Header "LICENCE AND COPYRIGHT" Copyright (c) 2005\-2011, Damian Conway \f(CW\*(C`\*(C'\fR. All rights reserved. .PP This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. .SH "DISCLAIMER OF WARRANTY" .IX Header "DISCLAIMER OF WARRANTY" \&\s-1BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE \*(L"AS IS\*(R" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.\s0 .PP \&\s-1IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE \s0(\s-1INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE\s0), \s-1EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\s0