1Contextual::Return(3) User Contributed Perl DocumentationContextual::Return(3)
2
3
4

NAME

6       Contextual::Return - Create context-sensitive return values
7

VERSION

9       This document describes Contextual::Return version 0.004014
10

SYNOPSIS

12           use Contextual::Return;
13           use Carp;
14
15           sub foo {
16               return
17                   SCALAR { 'thirty-twelve' }
18                   LIST   { 1,2,3 }
19
20                   BOOL { 1 }
21                   NUM  { 7*6 }
22                   STR  { 'forty-two' }
23
24                   HASHREF  { {name => 'foo', value => 99} }
25                   ARRAYREF { [3,2,1] }
26
27                   GLOBREF  { \*STDOUT }
28                   CODEREF  { croak "Don't use this result as code!"; }
29               ;
30           }
31
32           # and later...
33
34           if (my $foo = foo()) {
35               for my $count (1..$foo) {
36                   print "$count: $foo is:\n"
37                       . "  array: @{$foo}\n"
38                       . "  hash:  $foo->{name} => $foo->{value}\n"
39                       ;
40               }
41               print {$foo} $foo->();
42           }
43

DESCRIPTION

45       Usually, when you need to create a subroutine that returns different
46       values in different contexts (list, scalar, or void), you write
47       something like:
48
49           sub get_server_status {
50               my ($server_ID) = @_;
51
52               # Acquire server data somehow...
53               my %server_data = _ascertain_server_status($server_ID);
54
55               # Return different components of that data,
56               # depending on call context...
57               if (wantarray()) {
58                   return @server_data{ qw(name uptime load users) };
59               }
60               if (defined wantarray()) {
61                   return $server_data{load};
62               }
63               if (!defined wantarray()) {
64                   carp 'Useless use of get_server_status() in void context';
65                   return;
66               }
67               else {
68                   croak q{Bad context! No biscuit!};
69               }
70           }
71
72       That works okay, but the code could certainly be more readable. In its
73       simplest usage, this module makes that code more readable by providing
74       three subroutines--LIST(), SCALAR(), VOID()--that are true only when
75       the current subroutine is called in the corresponding context:
76
77           use Contextual::Return;
78
79           sub get_server_status {
80               my ($server_ID) = @_;
81
82               # Acquire server data somehow...
83               my %server_data = _ascertain_server_status($server_ID);
84
85               # Return different components of that data
86               # depending on call context...
87               if (LIST)   { return @server_data{ qw(name uptime load users) } }
88               if (SCALAR) { return $server_data{load}                         }
89               if (VOID)   { print "$server_data{load}\n"                      }
90               else        { croak q{Bad context! No biscuit!}                 }
91           }
92
93   Contextual returns
94       Those three subroutines can also be used in another way: as labels on a
95       series of contextual return blocks (collectively known as a contextual
96       return sequence). When a context sequence is returned, it automatically
97       selects the appropriate contextual return block for the calling
98       context.  So the previous example could be written even more cleanly
99       as:
100
101           use Contextual::Return;
102
103           sub get_server_status {
104               my ($server_ID) = @_;
105
106               # Acquire server data somehow...
107               my %server_data = _ascertain_server_status($server_ID);
108
109               # Return different components of that data
110               # depending on call context...
111               return (
112                   LIST    { return @server_data{ qw(name uptime load users) } }
113                   SCALAR  { return $server_data{load}                         }
114                   VOID    { print "$server_data{load}\n"                      }
115                   DEFAULT { croak q{Bad context! No biscuit!}                 }
116               );
117           }
118
119       The context sequence automatically selects the appropriate block for
120       each call context.
121
122   Lazy contextual return values
123       "LIST" and "VOID" blocks are always executed during the "return"
124       statement. However, scalar return blocks ("SCALAR", "STR", "NUM",
125       "BOOL", etc.) blocks are not. Instead, returning any of scalar block
126       types causes the subroutine to return an object that lazily evaluates
127       that block only when the return value is used.
128
129       This means that returning a "SCALAR" block is a convenient way to
130       implement a subroutine with a lazy return value. For example:
131
132           sub digest {
133               return SCALAR {
134                   my ($text) = @_;
135                   md5($text);
136               }
137           }
138
139           my $digest = digest($text);
140
141           print $digest;   # md5() called only when $digest used as string
142
143       To better document this usage, the "SCALAR" block has a synonym:
144       "LAZY".
145
146           sub digest {
147               return LAZY {
148                   my ($text) = @_;
149                   md5($text);
150               }
151           }
152
153   Active contextual return values
154       Once a return value has been lazily evaluated in a given context, the
155       resulting value is cached, and thereafter reused in that same context.
156
157       However, you can specify that, rather than being cached, the value
158       should be re-evaluated every time the value is used:
159
160            sub make_counter {
161               my $counter = 0;
162               return ACTIVE
163                   SCALAR   { ++$counter }
164                   ARRAYREF { [1..$counter] }
165           }
166
167           my $idx = make_counter();
168
169           print "$idx\n";      # 1
170           print "$idx\n";      # 2
171           print "[@$idx]\n";   # [1 2]
172           print "$idx\n";      # 3
173           print "[@$idx]\n";   # [1 2 3]
174
175   Semi-lazy contextual return values
176       Sometimes, single or repeated lazy evaluation of a scalar return value
177       in different contexts isn't what you really want. Sometimes what you
178       really want is for the return value to be lazily evaluated once only
179       (the first time it's used in any context), and then for that first
180       value to be reused whenever the return value is subsequently
181       reevaluated in any other context.
182
183       To get that behaviour, you can use the "FIXED" modifier, which causes
184       the return value to morph itself into the actual value the first time
185       it is used. For example:
186
187           sub lazy {
188               return
189                   SCALAR { 42 }
190                   ARRAYREF { [ 1, 2, 3 ] }
191               ;
192           }
193
194           my $lazy = lazy();
195           print $lazy + 1;            # 43
196           print "@{$lazy}";           # 1 2 3
197
198
199           sub semilazy {
200               return FIXED
201                   SCALAR { 42 }
202                   ARRAYREF { [ 1, 2, 3 ] }
203               ;
204           }
205
206           my $semi = semilazy();
207           print $semi + 1;            # 43
208           print "@{$semi}";           # die q{Can't use string ("42") as an ARRAY ref}
209
210   Finer distinctions of scalar context
211       Because the scalar values returned from a context sequence are lazily
212       evaluated, it becomes possible to be more specific about what kind of
213       scalar value should be returned: a boolean, a number, or a string. To
214       support those distinctions, Contextual::Return provides four extra
215       context blocks: "NUM", "STR", "BOOL", and "PUREBOOL":
216
217           sub get_server_status {
218               my ($server_ID) = @_;
219
220               # Acquire server data somehow...
221               my %server_data = _ascertain_server_status($server_ID);
222
223               # Return different components of that data
224               # depending on call context...
225               return (
226                      LIST { @server_data{ qw(name uptime load users) }          }
227                  PUREBOOL { $_ = $server_data{uptime}; $server_data{uptime} > 0 }
228                      BOOL { $server_data{uptime} > 0                            }
229                      NUM  { $server_data{load}                                  }
230                      STR  { "$server_data{name}: $server_data{uptime}"          }
231                      VOID { print "$server_data{load}\n"                        }
232                   DEFAULT { croak q{Bad context! No biscuit!}                   }
233               );
234           }
235
236       With these in place, the object returned from a scalar-context call to
237       get_server_status() now behaves differently, depending on how it's
238       used. For example:
239
240           if ( my $status = get_server_status() ) {  # BOOL: True if uptime > 0
241               $load_distribution[$status]++;         # INT:  Evaluates to load value
242               print "$status\n";                     # STR:  Prints "name: uptime"
243           }
244
245           if (get_server_status()) {                 # PUREBOOL: also sets $_;
246               print;                                 # ...which is then used here
247           }
248
249       Boolean vs Pure Boolean contexts
250
251       There is a special subset of boolean contexts where the return value is
252       being used and immediately thrown away. For example, in the loop:
253
254           while (get_data()) {
255               ...
256           }
257
258       the value returned by get_data() is tested for truth and then
259       discarded.  This is known as "pure boolean context". In contrast, in
260       the loop:
261
262           while (my $data = get_data()) {
263               ...
264           }
265
266       the value returned by get_data() is first assigned to $data, then
267       tested for truth. Because of the assignment, the return value is not
268       discarded after the boolean test. This is ordinary "boolean context".
269
270       In Perl, pure boolean context is often associated with a special side-
271       effect, that does not occur in regular boolean contexts. For example:
272
273           while (<>) {...}         # $_ set as side-effect of pure boolean context
274
275           while ($v = <>) {...}    # $_ NOT set in ordinary boolean context
276
277       Contextual::Return supports this with a special subcase of "BOOL" named
278       <PUREBOOL>. In pure boolean contexts, Contextual::Return will call a
279       "PUREBOOL" handler if one has been defined, or fall back to a "BOOL" or
280       "SCALAR" handler if no "PUREBOOL" handler exists. In ordinary boolean
281       contexts only the "BOOL" or "SCALAR" handlers are tried, even if a
282       "PUREBOOL" handler is also defined.
283
284       Typically "PUREBOOL" handlers are set up to have some side-effect (most
285       commonly: setting $_ or <$@>), like so:
286
287           sub get_data {
288               my ($succeeded, @data) = _go_and_get_data();
289
290               return
291                   PUREBOOL { $_ = $data[0]; $succeeded; }
292                       BOOL {                $succeeded; }
293                     SCALAR {                $data[0];   }
294                       LIST {                @data;      }
295           }
296
297       However, there is no requirement that they have side-effects. For
298       example, they can also be used to implement "look-but-don't-retrieve-
299       yet" checking:
300
301           sub get_data {
302               my $data;
303               return
304                   PUREBOOL {        _check_for_but_dont_get_data();   }
305                       BOOL { defined( $data ||= _go_and_get_data() ); }
306                        REF {          $data ||= _go_and_get_data();   }
307           }
308
309   Self-reference within handlers
310       Any handler can refer to the contextual return object it is part of, by
311       calling the RETOBJ() function. This is particularly useful for
312       "PUREBOOL" and "LIST" handlers. For example:
313
314           return
315               PUREBOOL { $_ = RETOBJ; next handler; }
316                   BOOL { !$failed;                  }
317                DEFAULT { $data;                     };
318
319   Referential contexts
320       The other major kind of scalar return value is a reference.
321       Contextual::Return provides contextual return blocks that allow you to
322       specify what to (lazily) return when the return value of a subroutine
323       is used as a reference to a scalar ("SCALARREF {...}"), to an array
324       ("ARRAYREF {...}"), to a hash ("HASHREF {...}"), to a subroutine
325       ("CODEREF {...}"), or to a typeglob ("GLOBREF {...}").
326
327       For example, the server status subroutine shown earlier could be
328       extended to allow it to return a hash reference, thereby supporting
329       "named return values":
330
331           sub get_server_status {
332               my ($server_ID) = @_;
333
334               # Acquire server data somehow...
335               my %server_data = _ascertain_server_status($server_ID);
336
337               # Return different components of that data
338               # depending on call context...
339               return (
340                      LIST { @server_data{ qw(name uptime load users) }  }
341                      BOOL { $server_data{uptime} > 0                    }
342                       NUM { $server_data{load}                          }
343                       STR { "$server_data{name}: $server_data{uptime}"  }
344                      VOID { print "$server_data{load}\n"                }
345                   HASHREF { return \%server_data                        }
346                   DEFAULT { croak q{Bad context! No biscuit!}           }
347               );
348           }
349
350           # and later...
351
352           my $users = get_server_status->{users};
353
354
355           # or, lazily...
356
357           my $server = get_server_status();
358
359           print "$server->{name} load = $server->{load}\n";
360
361   Interpolative referential contexts
362       The "SCALARREF {...}" and "ARRAYREF {...}" context blocks are
363       especially useful when you need to interpolate a subroutine into
364       strings. For example, if you have a subroutine like:
365
366           sub get_todo_tasks {
367               return (
368                   SCALAR { scalar @todo_list }      # How many?
369                   LIST   { @todo_list        }      # What are they?
370               );
371           }
372
373           # and later...
374
375           print "There are ", scalar(get_todo_tasks()), " tasks:\n",
376                   get_todo_tasks();
377
378       then you could make it much easier to interpolate calls to that
379       subroutine by adding:
380
381           sub get_todo_tasks {
382               return (
383                   SCALAR { scalar @todo_list }      # How many?
384                   LIST   { @todo_list        }      # What are they?
385
386                   SCALARREF { \scalar @todo_list }  # Ref to how many
387                   ARRAYREF  { \@todo_list        }  # Ref to them
388               );
389           }
390
391           # and then...
392
393           print "There are ${get_todo_tasks()} tasks:\n@{get_todo_tasks()}";
394
395       In fact, this behaviour is so useful that it's the default. If you
396       don't provide an explicit "SCALARREF {...}" block, Contextual::Return
397       automatically provides an implicit one that simply returns a reference
398       to whatever would have been returned in scalar context.  Likewise, if
399       no "ARRAYREF {...}" block is specified, the module supplies one that
400       returns the list-context return value wrapped up in an array reference.
401
402       So you could just write:
403
404           sub get_todo_tasks {
405               return (
406                   SCALAR { scalar @todo_list }      # How many?
407                   LIST   { @todo_list        }      # What are they?
408               );
409           }
410
411           # and still do this...
412
413           print "There are ${get_todo_tasks()} tasks:\n@{get_todo_tasks()}";
414
415   Fallback contexts
416       As the previous sections imply, the "BOOL {...}", "NUM {...}", "STR
417       {...}", and various "*REF {...}" blocks, are special cases of the
418       general "SCALAR {...}" context block. If a subroutine is called in one
419       of these specialized contexts but does not use the corresponding
420       context block, then the more general "SCALAR {...}" block is used
421       instead (if it has been specified).
422
423       So, for example:
424
425           sub read_value_from {
426               my ($fh) = @_;
427
428               my $value = <$fh>;
429               chomp $value;
430
431               return (
432                   BOOL   { defined $value }
433                   SCALAR { $value         }
434               );
435           }
436
437       ensures that the read_value_from() subroutine returns true in boolean
438       contexts if the read was successful. But, because no specific "NUM
439       {...}" or "STR {...}" return behaviours were specified, the subroutine
440       falls back on using its generic "SCALAR {...}" block in all other
441       scalar contexts.
442
443       Another way to think about this behaviour is that the various kinds of
444       scalar context blocks form a hierarchy:
445
446           SCALAR
447                ^
448                |
449                |--< BOOL
450                |
451                |--< NUM
452                |
453                `--< STR
454
455       Contextual::Return uses this hierarchical relationship to choose the
456       most specific context block available to handle any particular return
457       context, working its way up the tree from the specific type it needs,
458       to the more general type, if that's all that is available.
459
460       There are two slight complications to this picture. The first is that
461       Perl treats strings and numbers as interconvertable so the diagram (and
462       the Contextual::Return module) also has to allow these interconversions
463       as a fallback strategy:
464
465           SCALAR
466                ^
467                |
468                |--< BOOL
469                |
470                |--< NUM
471                |    : ^
472                |    v :
473                `--< STR
474
475       The dotted lines are meant to indicate that this intraconversion is
476       secondary to the main hierarchical fallback. That is, in a numeric
477       context, a "STR {...}" block will only be used if there is no "NUM
478       {...}" block and no "SCALAR {...}" block. In other words, the generic
479       context type is always used in preference to string<->number
480       conversion.
481
482       The second slight complication is that the above diagram only shows a
483       small part of the complete hierarchy of contexts supported by
484       Contextual::Return. The full fallback hierarchy (including dotted
485       interconversions) is:
486
487             DEFAULT
488                ^
489                |
490                |--< VOID
491                |
492                `--< NONVOID
493                        ^
494                        |
495                        |--< VALUE <...............
496                        |      ^                   :
497                        |      |                   :
498                        |      |--< SCALAR <.......:...
499                        |      |           ^           :
500                        |      |           |           :
501                        |      |           |--< BOOL   :
502                        |      |           |     ^     :
503                        |      |           |     |     :
504                        |      |           |  PUREBOOL :
505                        |      |           |           :
506                        |      |           |--< NUM <..:.
507                        |      |           |    : ^      :
508                        |      |           |    v :      :
509                        |      |           `--< STR <....:..
510                        |      |                           :
511                        |      |                          ::
512                        |      `--< LIST ................: :
513                        |            : ^                   :
514                        |            : :                   :
515                        `--- REF     : :                   :
516                              ^      : :                   :
517                              |      v :                   :
518                              |--< ARRAYREF                :
519                              |                            :
520                              |--< SCALARREF .............:
521                              |
522                              |--< HASHREF
523                              |
524                              |--< CODEREF
525                              |
526                              |--< GLOBREF
527                              |
528                              `--< OBJREF <....... METHOD
529                                      ^
530                                      :........... BLESSED
531
532       As before, each dashed arrow represents a fallback relationship. That
533       is, if the required context specifier isn't available, the arrows are
534       followed until a more generic one is found. The dotted arrows again
535       represent the interconversion of return values, which is attempted only
536       after the normal hierarchical fallback fails.
537
538       For example, if a subroutine is called in a context that expects a
539       scalar reference, but no "SCALARREF {...}" block is provided, then
540       Contextual::Return tries the following blocks in order:
541
542               REF {...}
543           NONVOID {...}
544           DEFAULT {...}
545               STR {...} (automatically taking a reference to the result)
546               NUM {...} (automatically taking a reference to the result)
547            SCALAR {...} (automatically taking a reference to the result)
548             VALUE {...} (automatically taking a reference to the result)
549
550       Likewise, in a list context, if there is no "LIST {...}" context block,
551       the module tries:
552
553              VALUE {...}
554            NONVOID {...}
555            DEFAULT {...}
556           ARRAYREF {...} (automatically dereferencing the result)
557                STR {...} (treating it as a list of one element)
558                NUM {...} (treating it as a list of one element)
559             SCALAR {...} (treating it as a list of one element)
560
561       The more generic context blocks are especially useful for intercepting
562       unexpected and undesirable call contexts. For example, to turn off the
563       automatic scalar-ref and array-ref interpolative behaviour described in
564       "Interpolative referential contexts", you could intercept all
565       referential contexts using a generic "REF {...}" context block:
566
567           sub get_todo_tasks {
568               return (
569                   SCALAR { scalar @todo_list }      # How many?
570                   LIST   { @todo_list        }      # What are they?
571
572                   REF { croak q{get_todo_task() can't be used as a reference} }
573               );
574           }
575
576           print 'There are ', get_todo_tasks(), '...';    # Still okay
577           print "There are ${get_todo_tasks()}...";       # Throws an exception
578
579   Treating return values as objects
580       Normally, when a return value is treated as an object (i.e. has a
581       method called on it), Contextual::Return invokes any "OBJREF" handler
582       that was specified in the contextual return list, and delegates the
583       method call to the object returned by that handler.
584
585       However, you can also be more specific, by specifying a "METHOD"
586       context handler in the contextual return list. The block of this
587       handler is expected to return one or more method-name/method-handler
588       pairs, like so:
589
590           return
591               METHOD {
592                   get_count => sub { my $n = shift; $data[$n]{count} },
593                   get_items => sub { my $n = shift; $data[$n]{items} },
594                   clear     => sub { @data = (); },
595                   reset     => sub { @data = (); },
596               }
597
598       Then, whenever one of the specified methods is called on the return
599       value, the corresponding subroutine will be called to implement it.
600
601       The method handlers must always be subroutine references, but the
602       method-name specifiers may be strings (as in the previous example) or
603       they may be specified generically, as either regexes or array
604       references. Generic method names are used to call the same handler for
605       two or more distinct method names.  For example, the previous example
606       could be simplified to:
607
608           return
609               METHOD {
610                   qr/get_(\w+)/     => sub { my $n = shift; $data[$n]{$1} },
611                   ['clear','reset'] => sub { @data = (); },
612               }
613
614       A method name specified by regex will invoke the corresponding handler
615       for any method call request that the regex matches. A method name
616       specified by array ref will invoke the corresponding handler if the
617       method requested matches any of the elements of the array (which may
618       themselves be strings or regexes).
619
620       When the method handler is invoked, the name of the method requested is
621       passed to the handler in $_, and the method's argument list is passed
622       (as usual) via @_.
623
624       Note that any methods not explicitly handled by the "METHOD" handlers
625       will still be delegated to the object returned by the "OBJREF" handler
626       (if it is also specified).
627
628   Not treating return values as objects
629       The use of "OBJREF" and "METHOD" are slightly complicated by the fact
630       that contextual return values are themselves objects.
631
632       For example, prior to version 0.4.4 of the module, if you passed a
633       contextual return value to Scalar::Util::blessed(), it always returned
634       a true value (namely, the string: 'Contextual::Return::Value'), even if
635       the return value had not specified handlers for "OBJREF" or "METHOD".
636
637       In other words, the implementation of contextual return values (as
638       objects) was getting in the way of the use of contextual return values
639       (as non-objects).
640
641       So the module now also provides a "BLESSED" handler, which allows you
642       to explicitly control how contextual return values interact with
643       Scalar::Util::blessed().
644
645       If $crv is a contextual return value, by default
646       Scalar::Util::blessed($crv) will now only return true if that return
647       value has a "OBJREF", "LAZY", "REF", "SCALAR", "VALUE", "NONVOID", or
648       "DEFAULT" handler that in turn returns a blessed object.
649
650       However if $crv also provides a "BLESSED" handler, blessed() will
651       return whatever that handler returns.
652
653       This means:
654
655           sub simulate_non_object {
656               return BOOL { 1 }
657                       NUM { 42 }
658           }
659
660           sub simulate_real_object {
661               return OBJREF { bless {}, 'My::Class' }
662                        BOOL { 1 }
663                         NUM { 42 }
664           }
665
666           sub simulate_faked_object {
667               return BLESSED { 'Foo' }
668                         BOOL { 1 }
669                          NUM { 42 }
670           }
671
672           sub simulate_previous_behaviour {
673               return BLESSED { 'Contextual::Return::Value' }
674                         BOOL { 1 }
675                          NUM { 42 }
676           }
677
678
679           say blessed( simulate_non_object()         );   # undef
680           say blessed( simulate_real_object()        );   # My::Class
681           say blessed( simulate_faked_object()       );   # Foo
682           say blessed( simulate_previous_behaviour() );   # Contextual::Return::Value
683
684       Typically, you either want no "BLESSED" handler (in which case
685       contextual return values pretend not to be blessed objects), or you
686       want "BLESSED { 'Contextual::Return::Value' }" for backwards
687       compatibility with pre-v0.4.7 behaviour.
688
689       Preventing fallbacks
690
691       Sometimes fallbacks can be too helpful. Or sometimes you want to impose
692       strict type checking on a return value.
693
694       Contextual::Returns allows that via the "STRICT" specifier. If you
695       include "STRICT" anywhere in your return statement, the module disables
696       all fallbacks and will therefore through an exception if the return
697       value is used in any way not explicitly specified in the contextual
698       return sequence.
699
700       For example, to create a subroutine that returns only a string:
701
702           sub get_name {
703               return STRICT STR { 'Bruce' }
704           }
705
706       If the return value of the subroutine is used in any other way than as
707       a string, an exception will be thrown.
708
709       You can still specify handlers for more than a single kind of context
710       when using "STRICT":
711
712           sub get_name {
713               return STRICT
714                   STR  { 'Bruce' }
715                   BOOL { 0 }
716           }
717
718       ...but these will still be the only contexts in which the return value
719       can be used:
720
721           my $n = get_name() ? 1 : 2;  # Okay because BOOL handler specified
722
723           my $n = 'Dr' . get_name();   # Okay because STR handler specified
724
725           my $n = 1 + get_name();      # Exception thrown because no NUM handler
726
727       In other words, "STRICT" allows you to impose strict type checking on
728       your contextual return value.
729
730   Deferring handlers
731       Because the various handlers form a hierarchy, it's possible to
732       implement more specific handlers by falling back on ("deferring to")
733       more general ones. For example, a "PUREBOOL" handler is almost always
734       identical in its basic behaviour to the corresponding "BOOL" handler,
735       except that it adds some side-effect.  For example:
736
737           return
738               PUREBOOL { $_ = $return_val; defined $return_val && $return_val > 0 }
739                   BOOL {                   defined $return_val && $return_val > 0 }
740                 SCALAR {                   $return_val;                           }
741
742       So Contextual::Return allows you to have a handler perform some action
743       and then defer to a more general handler to supply the actual return
744       value. To fall back to a more general case in this way, you simply
745       write:
746
747           next handler;
748
749       at the end of the handler in question, after which Contextual::Return
750       will find the next-most-specific handler and execute it as well. So the
751       previous example, could be re-written:
752
753           return
754               PUREBOOL { $_ = $return_val; next handler;        }
755                   BOOL { defined $return_val && $return_val > 0 }
756                 SCALAR { $return_val;                           }
757
758       Note that any specific handler can defer to a more general one in this
759       same way. For example, you could provide consistent and maintainable
760       type-checking for a subroutine that returns references by providing
761       "ARRAYREF", "HASHREF", and "SCALARREF" handlers that all defer to a
762       generic "REF" handler, like so:
763
764           my $retval = _get_ref();
765
766           return
767              SCALARREF { croak 'Type mismatch' if ref($retval) ne 'SCALAR';
768                          next handler;
769                        }
770               ARRAYREF { croak 'Type mismatch' if ref($retval) ne 'ARRAY';
771                          next handler;
772                        }
773                HASHREF { croak 'Type mismatch' if ref($retval) ne 'HASH';
774                          next handler;
775                        }
776                    REF { $retval }
777
778       If, at a later time, the process of returning a reference became more
779       complex, only the "REF" handler would have to be updated.
780
781   Nested handlers
782       Another way of factoring out return behaviour is to nest more specific
783       handlers inside more general ones. For instance, in the final example
784       given in "Boolean vs Pure Boolean contexts":
785
786           sub get_data {
787               my $data;
788               return
789                   PUREBOOL {        _check_for_but_dont_get_data();   }
790                       BOOL { defined( $data ||= _go_and_get_data() ); }
791                        REF {          $data ||= _go_and_get_data();   }
792           }
793
794       you could factor out the repeated calls to _go_and_get_data() like so:
795
796           sub get_data {
797               return
798                   PUREBOOL { _check_for_but_dont_get_data(); }
799                    DEFAULT {
800                       my $data = _go_and_get_data();
801
802                       BOOL { defined $data; }
803                        REF {         $data; }
804                    }
805           }
806
807       Here, the "DEFAULT" handler deals with every return context except pure
808       boolean. Within that "DEFAULT" handler, the data is first retrieved,
809       and then two "sub-handlers" deal with the ordinary boolean and
810       referential contexts.
811
812       Typically nested handlers are used in precisely this way: to optimize
813       for inexpensive special cases (such as pure boolean or integer or void
814       return contexts) and only do extra work for those other cases that
815       require it.
816
817   Failure contexts
818       Two of the most common ways to specify that a subroutine has failed are
819       to return a false value, or to throw an exception. The
820       Contextual::Return module provides a mechanism that allows the
821       subroutine writer to support both of these mechanisms at the same time,
822       by using the "FAIL" specifier.
823
824       A return statement of the form:
825
826           return FAIL;
827
828       causes the surrounding subroutine to return "undef" (i.e. false) in
829       boolean contexts, and to throw an exception in any other context. For
830       example:
831
832           use Contextual::Return;
833
834           sub get_next_val {
835               my $next_val = <>;
836               return FAIL if !defined $next_val;
837               chomp $next_val;
838               return $next_val;
839           }
840
841       If the "return FAIL" statement is executed, it will either return false
842       in a boolean context:
843
844           if (my $val = get_next_val()) {      # returns undef if no next val
845               print "[$val]\n";
846           }
847
848       or else throw an exception if the return value is used in any other
849       context:
850
851           print get_next_val();       # throws exception if no next val
852
853           my $next_val = get_next_val();
854           print "[$next_val]\n";      # throws exception if no next val
855
856       The exception that is thrown is of the form:
857
858           Call to main::get_next_val() failed at demo.pl line 42
859
860       but you can change that message by providing a block to the "FAIL",
861       like so:
862
863           return FAIL { "No more data" } if !defined $next_val;
864
865       in which case, the final value of the block becomes the exception
866       message:
867
868           No more data at demo.pl line 42
869
870       A failure value can be interrogated for its error message, by calling
871       its error() method, like so:
872
873           my $val = get_next_val();
874           if ($val) {
875               print "[$val]\n";
876           }
877           else {
878               print $val->error, "\n";
879           }
880
881   Configurable failure contexts
882       The default "FAIL" behaviour--false in boolean context, fatal in all
883       others--works well in most situations, but violates the Platinum Rule
884       ("Do unto others as they would have done unto them").
885
886       So it may be user-friendlier if the user of a module is allowed decide
887       how the module's subroutines should behave on failure. For example, one
888       user might prefer that failing subs always return undef; another might
889       prefer that they always throw an exception; a third might prefer that
890       they always log the problem and return a special Failure object; whilst
891       a fourth user might want to get back 0 in scalar contexts, an empty
892       list in list contexts, and an exception everywhere else.
893
894       You could create a module that allows the user to specify all these
895       alternatives, like so:
896
897           package MyModule;
898           use Contextual::Return;
899           use Log::StdLog;
900
901           sub import {
902               my ($package, @args) = @_;
903
904               Contextual::Return::FAIL_WITH {
905                   ':false' => sub { return undef },
906                   ':fatal' => sub { croak @_       },
907                   ':filed' => sub {
908                                   print STDLOG 'Sub ', (caller 1)[3], ' failed';
909                                   return Failure->new();
910                               },
911                   ':fussy' => sub {
912                                   SCALAR  { undef      }
913                                   LIST    { ()         }
914                                   DEFAULT { croak @_ }
915                               },
916               }, @args;
917           }
918
919       This configures Contextual::Return so that, instead of the usual false-
920       or-fatal semantics, every "return FAIL" within MyModule's namespace is
921       implemented by one of the four subroutines specified in the hash that
922       was passed to "FAIL_WITH".
923
924       Which of those four subs implements the "FAIL" is determined by the
925       arguments passed after the hash (i.e. by the contents of @args).
926       "FAIL_WITH" walks through that list of arguments and compares them
927       against the keys of the hash. If a key matches an argument, the
928       corresponding value is used as the implementation of "FAIL". Note that,
929       if subsequent arguments also match a key, their subroutine overrides
930       the previously installed implementation, so only the final override has
931       any effect. Contextual::Return generates warnings when multiple
932       overrides are specified.
933
934       All of which mean that, if a user loaded the MyModule module like this:
935
936           use MyModule qw( :fatal other args here );
937
938       then every "FAIL" within MyModule would be reconfigured to throw an
939       exception in all circumstances, since the presence of the ':fatal' in
940       the argument list will cause "FAIL_WITH" to select the hash entry whose
941       key is ':fatal'.
942
943       On the other hand, if they loaded the module:
944
945           use MyModule qw( :fussy other args here );
946
947       then each "FAIL" within MyModule would return undef or empty list or
948       throw an exception, depending on context, since that's what the
949       subroutine whose key is ':fussy' does.
950
951       Many people prefer module interfaces with a "flag => value" format, and
952       "FAIL_WITH" supports this too. For example, if you wanted your module
953       to take a "-fail" flag, whose associated value could be any of
954       "undefined", "exception", "logged", or "context", then you could
955       implement that simply by specifying the flag as the first argument
956       (i.e. before the hash) like so:
957
958           sub import {
959               my $package = shift;
960
961               Contextual::Return::FAIL_WITH -fail => {
962                   'undefined' => sub { return undef },
963                   'exception' => sub { croak @_ },
964                   'logged'    => sub {
965                                   print STDLOG 'Sub ', (caller 1)[3], ' failed';
966                                   return Failure->new();
967                               },
968                   'context' => sub {
969                                   SCALAR  { undef      }
970                                   LIST    { ()         }
971                                   DEFAULT { croak @_ }
972                               },
973               }, @_;
974
975       and then load the module:
976
977           use MyModule qw( other args here ), -fail=>'undefined';
978
979       or:
980
981           use MyModule qw( other args here ), -fail=>'exception';
982
983       In this case, "FAIL_WITH" scans the argument list for a pair of values:
984       its flag string, followed by some other selector value. Then it looks
985       up the selector value in the hash, and installs the corresponding
986       subroutine as its local "FAIL" handler.
987
988       If this "flagged" interface is used, the user of the module can also
989       specify their own handler directly, by passing a subroutine reference
990       as the selector value instead of a string:
991
992           use MyModule qw( other args here ), -fail=>sub{ die 'horribly'};
993
994       If this last example were used, any call to "FAIL" within MyModule
995       would invoke the specified anonymous subroutine (and hence throw a
996       'horribly' exception).
997
998       Note that, any overriding of a "FAIL" handler is specific to the
999       namespace and file from which the subroutine that calls "FAIL_WITH" is
1000       itself called. Since "FAIL_WITH" is designed to be called from within a
1001       module's import() subroutine, that generally means that the "FAIL"s
1002       within a given module X are only overridden for the current namespace
1003       within the particular file from module X is loaded. This means that two
1004       separate pieces of code (in separate files or separate namespaces) can
1005       each independently override a module's "FAIL" behaviour, without
1006       interfering with each other.
1007
1008   Lvalue contexts
1009       Recent versions of Perl offer (limited) support for lvalue subroutines:
1010       subroutines that return a modifiable variable, rather than a simple
1011       constant value.
1012
1013       Contextual::Return can make it easier to create such subroutines,
1014       within the limitations imposed by Perl itself. The limitations that
1015       Perl places on lvalue subs are:
1016
1017       1.  The subroutine must be declared with an ":lvalue" attribute:
1018
1019               sub foo :lvalue {...}
1020
1021       2.  The subroutine must not return via an explicit "return". Instead,
1022           the last statement must evaluate to a variable, or must be a call
1023           to another lvalue subroutine call.
1024
1025               my ($foo, $baz);
1026
1027               sub foo :lvalue {
1028                   $foo;               # last statement evals to a var
1029               }
1030
1031               sub bar :lvalue {
1032                   foo();              # last statement is lvalue sub call
1033               }
1034
1035               sub baz :lvalue {
1036                   my ($arg) = @_;
1037
1038                   $arg > 0            # last statement evals...
1039                       ? $baz          # ...to a var
1040                       : bar();        # ...or to an lvalue sub call
1041               }
1042
1043       Thereafter, any call to the lvalue subroutine produces a result that
1044       can be assigned to:
1045
1046           baz(0) = 42;            # same as: $baz = 42
1047
1048           baz(1) = 84;            # same as:                  bar() = 84
1049                                   #  which is the same as:    foo() = 84
1050                                   #   which is the same as:   $foo  = 84
1051
1052       Ultimately, every lvalue subroutine must return a scalar variable,
1053       which is then used as the lvalue of the assignment (or whatever other
1054       lvalue operation is applied to the subroutine call). Unfortunately,
1055       because the subroutine has to return this variable before the
1056       assignment can take place, there is no way that a normal lvalue
1057       subroutine can get access to the value that will eventually be assigned
1058       to its return value.
1059
1060       This is occasionally annoying, so the Contextual::Return module offers
1061       a solution: in addition to all the context blocks described above, it
1062       provides three special contextual return blocks specifically for use in
1063       lvalue subroutines: "LVALUE", "RVALUE", and "NVALUE".
1064
1065       Using these blocks you can specify what happens when an lvalue
1066       subroutine is used in lvalue and non-lvalue (rvalue) context. For
1067       example:
1068
1069           my $verbosity_level = 1;
1070
1071           # Verbosity values must be between 0 and 5...
1072           sub verbosity :lvalue {
1073               LVALUE { $verbosity_level = max(0, min($_, 5)) }
1074               RVALUE { $verbosity_level                      }
1075           }
1076
1077       The "LVALUE" block is executed whenever "verbosity" is called as an
1078       lvalue:
1079
1080           verbosity() = 7;
1081
1082       The block has access to the value being assigned, which is passed to it
1083       as $_. So, in the above example, the assigned value of 7 would be
1084       aliased to $_ within the "LVALUE" block, would be reduced to 5 by the
1085       "min-of-max" expression, and then assigned to $verbosity_level.
1086
1087       (If you need to access the caller's $_, it's also still available: as
1088       $CALLER::_.)
1089
1090       When the subroutine isn't used as an lvalue:
1091
1092           print verbosity();
1093
1094       the "RVALUE" block is executed instead and its final value returned.
1095       Within an "RVALUE" block you can use any of the other features of
1096       Contextual::Return. For example:
1097
1098           sub verbosity :lvalue {
1099               LVALUE { $verbosity_level = int max(0, min($_, 5)) }
1100               RVALUE {
1101                   NUM  { $verbosity_level               }
1102                   STR  { $description[$verbosity_level] }
1103                   BOOL { $verbosity_level > 2           }
1104               }
1105           }
1106
1107       but the context sequence must be nested inside an "RVALUE" block.
1108
1109       You can also specify what an lvalue subroutine should do when it is
1110       used neither as an lvalue nor as an rvalue (i.e. in void context), by
1111       using an "NVALUE" block:
1112
1113           sub verbosity :lvalue {
1114               my ($level) = @_;
1115
1116               NVALUE { $verbosity_level = int max(0, min($level, 5)) }
1117               LVALUE { $verbosity_level = int max(0, min($_,     5)) }
1118               RVALUE {
1119                   NUM  { $verbosity_level               }
1120                   STR  { $description[$verbosity_level] }
1121                   BOOL { $verbosity_level > 2           }
1122               }
1123           }
1124
1125       In this example, a call to verbosity() in void context sets the
1126       verbosity level to whatever argument is passed to the subroutine:
1127
1128           verbosity(1);
1129
1130       Note that you cannot get the same effect by nesting a "VOID" block
1131       within an "RVALUE" block:
1132
1133               LVALUE { $verbosity_level = int max(0, min($_, 5)) }
1134               RVALUE {
1135                   NUM  { $verbosity_level               }
1136                   STR  { $description[$verbosity_level] }
1137                   BOOL { $verbosity_level > 2           }
1138                   VOID { $verbosity_level = $level      }  # Wrong!
1139               }
1140
1141       That's because, in a void context the return value is never evaluated,
1142       so it is never treated as an rvalue, which means the "RVALUE" block
1143       never executes.
1144
1145   Result blocks
1146       Occasionally, it's convenient to calculate a return value before the
1147       end of a contextual return block. For example, you may need to clean up
1148       external resources involved in the calculation after it's complete.
1149       Typically, this requirement produces a slightly awkward code sequence
1150       like this:
1151
1152           return
1153               VALUE {
1154                   $db->start_work();
1155                   my $result = $db->retrieve_query($query);
1156                   $db->commit();
1157                   $result;
1158               }
1159
1160       Such code sequences become considerably more awkward when you want the
1161       return value to be context sensitive, in which case you have to write
1162       either:
1163
1164           return
1165               LIST {
1166                   $db->start_work();
1167                   my @result = $db->retrieve_query($query);
1168                   $db->commit();
1169                   @result;
1170               }
1171               SCALAR {
1172                   $db->start_work();
1173                   my $result = $db->retrieve_query($query);
1174                   $db->commit();
1175                   $result;
1176               }
1177
1178       or, worse:
1179
1180           return
1181               VALUE {
1182                   $db->start_work();
1183                   my $result = LIST ? [$db->retrieve_query($query)]
1184                                     :  $db->retrieve_query($query);
1185                   $db->commit();
1186                   LIST ? @{$result} : $result;
1187               }
1188
1189       To avoid these infelicities, Contextual::Return provides a second way
1190       of setting the result of a context block; a way that doesn't require
1191       that the result be the last statement in the block:
1192
1193           return
1194               LIST {
1195                   $db->start_work();
1196                   RESULT { $db->retrieve_query($query) };
1197                   $db->commit();
1198               }
1199               SCALAR {
1200                   $db->start_work();
1201                   RESULT { $db->retrieve_query($query) };
1202                   $db->commit();
1203               }
1204
1205       The presence of a "RESULT" block inside a contextual return block
1206       causes that block to return the value of the final statement of the
1207       "RESULT" block as the handler's return value, rather than returning the
1208       value of the handler's own final statement. In other words, the
1209       presence of a "RESULT" block overrides the normal return value of a
1210       context handler.
1211
1212       Better still, the "RESULT" block always evaluates its final statement
1213       in the same context as the surrounding "return", so you can just write:
1214
1215           return
1216               VALUE {
1217                   $db->start_work();
1218                   RESULT { $db->retrieve_query($query) };
1219                   $db->commit();
1220               }
1221
1222       and the retrieve_query() method will be called in the appropriate
1223       context in all cases.
1224
1225       A "RESULT" block can appear anywhere inside any contextual return
1226       block, but may not be used outside a context block. That is, this is an
1227       error:
1228
1229           if ($db->closed) {
1230               RESULT { undef }; # Error: not in a context block
1231           }
1232           return
1233               VALUE {
1234                   $db->start_work();
1235                   RESULT { $db->retrieve_query($query) };
1236                   $db->commit();
1237               }
1238
1239   Post-handler clean-up
1240       If a subroutine uses an external resource, it's often necessary to
1241       close or clean-up that resource after the subroutine ends...regardless
1242       of whether the subroutine exits normally or via an exception.
1243
1244       Typically, this is done by encapsulating the resource in a lexically
1245       scoped object whose destructor does the clean-up. However, if the
1246       clean-up doesn't involve deallocation of an object (as in the
1247       "$db->commit()" example in the previous section), it can be annoying to
1248       have to create a class and allocate a container object, merely to
1249       mediate the clean-up.
1250
1251       To make it easier to manage such resources, Contextual::Return supplies
1252       a special labelled block: the "RECOVER" block. If a "RECOVER" block is
1253       specified as part of a contextual return sequence, that block is
1254       executed after any context handler, even if the context handler exits
1255       via an exception.
1256
1257       So, for example, you could implement a simple commit-or-revert policy
1258       like so:
1259
1260           return
1261               LIST    { $db->retrieve_all($query)  }
1262               SCALAR  { $db->retrieve_next($query) }
1263               RECOVER {
1264                   if ($@) {
1265                       $db->revert();
1266                   }
1267                   else {
1268                       $db->commit();
1269                   }
1270               }
1271
1272       The presence of a "RECOVER" block also intercepts all exceptions thrown
1273       in any other context block in the same contextual return sequence. Any
1274       such exception is passed into the "RECOVER" block in the usual manner:
1275       via the $@ variable. The exception may be rethrown out of the "RECOVER"
1276       block by calling "die":
1277
1278           return
1279               LIST    { $db->retrieve_all($query) }
1280               DEFAULT { croak "Invalid call (not in list context)" }
1281               RECOVER {
1282                   die $@ if $@;    # Propagate any exception
1283                   $db->commit();   # Otherwise commit the changes
1284               }
1285
1286       A "RECOVER" block can also access or replace the returned value, by
1287       invoking a "RESULT" block. For example:
1288
1289           return
1290               LIST    { attempt_to_generate_list_for(@_)  }
1291               SCALAR  { attempt_to_generate_count_for(@_) }
1292               RECOVER {
1293                   if ($@) {                # On any exception...
1294                       warn "Replacing return value. Previously: ", RESULT;
1295                       RESULT { undef }     # ...return undef
1296                   }
1297               }
1298
1299   Post-return clean-up
1300       Occasionally it's necessary to defer the clean-up of resources until
1301       after the return value has been used. Once again, this is usually done
1302       by returning an object with a suitable destructor.
1303
1304       Using Contextual::Return you can get the same effect, by providing a
1305       "CLEANUP" block in the contextual return sequence:
1306
1307           return
1308               LIST    { $db->retrieve_all($query)  }
1309               SCALAR  { $db->retrieve_next($query) }
1310               CLEANUP { $db->commit()              }
1311
1312       In this example, the "commit" method call is only performed after the
1313       return value has been used by the caller. Note that this is quite
1314       different from using a "RECOVER" block, which is called as the
1315       subroutine returns its value; a "CLEANUP" is called when the returned
1316       value is garbage collected.
1317
1318       A "CLEANUP" block is useful for controlling resources allocated to
1319       support an "ACTIVE" return value. For example:
1320
1321           my %file;
1322
1323           # Return an active value that is always the next line from a file...
1324           sub readline_from {
1325               my ($file_name) = @_;
1326
1327               # Open the file, if not already open...
1328               if (!$file{$file_name}) {
1329                   open $file{$file_name}{handle}, '<', $file_name;
1330               }
1331
1332               # Track how many active return values are using this file...
1333               $file{$file_name}{count}++;
1334
1335               return ACTIVE
1336                   # Evaluating the return value returns the next line...
1337                   VALUE   { readline $file{$file_name}{handle} }
1338
1339                   # Once the active value is finished with, clean up the filehandle...
1340                   CLEANUP {
1341                       delete $file{$file_name}
1342                           if --$file{$file_name}{count} == 0;
1343                   }
1344           }
1345
1346   Debugging contextual return values
1347       Contextual return values are implemented as opaque objects (using the
1348       "inside-out" technique). This means that passing such values to
1349       Data::Dumper produces an uninformative output like:
1350
1351           $VAR1 = bless( do{\(my $o = undef)}, 'Contextual::Return::Value' );
1352
1353       So the module provides two methods that allow contextual return values
1354       to be correctly reported: either directly, or when dumped by
1355       Data::Dumper.
1356
1357       To dump a contextual return value directly, call the module's DUMP()
1358       method explicitly and print the result:
1359
1360           print $crv->Contextual::Return::DUMP();
1361
1362       This produces an output something like:
1363
1364           [
1365            { FROM       => 'main::foo'                                       },
1366            { NO_HANDLER => [ 'VOID', 'CODEREF', 'HASHREF', 'GLOBREF' ]       },
1367            { FALLBACKS  => [ 'VALUE' ]                                       },
1368            { LIST       => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]                 },
1369            { STR        => '<<<Throws exception: Died at demo.pl line 7.>>>' },
1370            { NUM        => 42                                                },
1371            { BOOL       => -1                                                },
1372            { SCALARREF  => '<<<self-reference>>>'                            },
1373            { ARRAYREF   => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]                 },
1374           ];
1375
1376       The "FROM" hash entry names the subroutine that produced the return
1377       value. The "NO_HANDLER" hash entry lists those contexts for which no
1378       handler was defined (and which would therefore normally produce "can't
1379       call" exceptions such as: "Can't call main::foo in VOID context").  The
1380       "FALLBACKS" hash entry lists any "generic" contexts such as "VALUE",
1381       "NONVOID", "REF", "DEFAULT", etc. that the contextual return value can
1382       also handle. After these, all the remaining hash entries are actual
1383       contexts in which the return value could successfully be evaluated, and
1384       the value it would produce in each of those contexts.
1385
1386       The Data::Dumper module also has a mechanism by which you can tell it
1387       how to produce a similar listing automatically whenever a contextual
1388       return value is passed to its "Dumper" method. Data::Dumper allows you
1389       to register a "freezer" method, that is called prior to dumping, and
1390       which can be used to adapt an opaque object to make it dumpable.
1391       Contextual::Return provides just such a method
1392       (Contextual::Return::FREEZE()) for you to register, like so:
1393
1394           use Data::Dumper 'Dumper';
1395
1396           local $Data::Dumper::Freezer = 'Contextual::Return::FREEZE';
1397
1398           print Dumper $foo;
1399
1400       The output is then precisely the same as Contextual::Return::DUMP()
1401       would produce.
1402
1403       Note that, with both of the above dumping mechanisms, it is essential
1404       to use the full name of the method. That is:
1405
1406           print $crv->Contextual::Return::DUMP();
1407
1408       rather than:
1409
1410           print $crv->DUMP();
1411
1412       This is because the shorter version is interpreted as calling the
1413       DUMP() method on the object returned by the return value's "OBJREF"
1414       context block (see "Scalar reference contexts")
1415
1416       For the same reason, you must write:
1417
1418           local $Data::Dumper::Freezer = 'Contextual::Return::FREEZE';
1419
1420       not:
1421
1422           local $Data::Dumper::Freezer = 'FREEZE';
1423
1424   Namespace controls
1425       By default the module exports a large number of return context markers:
1426
1427           DEFAULT    REF          LAZY
1428           VOID       SCALARREF    FIXED
1429           NONVOID    ARRAYREF     ACTIVE
1430           LIST       CODEREF      RESULT
1431           SCALAR     HASHREF      RECOVER
1432           VALUE      GLOBREF      CLEANUP
1433           STR        OBJREF       RVALUE
1434           NUM        METHOD       LVALUE
1435           BOOL                    NVALUE
1436           PUREBOOL
1437
1438       These are exported as subroutines, and so can conflict with existing
1439       subroutines in your namespace, or with subroutines imported from other
1440       modules.
1441
1442       Contextual::Return allows you to control which contextual return blocks
1443       are exported into any namespace that uses the module. It also allows
1444       you to rename blocks to avoid namespace conflicts with existing
1445       subroutines.
1446
1447       Both these features are controlled by passing arguments to the "use"
1448       statement that loads the module as follows:
1449
1450       •   Any string passed as an argument to "use Contextual::Return",
1451           exports only the block name it specifies;
1452
1453       •   Any regex passed as an argument to "use Contextual::Return" exports
1454           every block name it matches;
1455
1456       •   Any array ref (recursively) exports each of its elements
1457
1458       •   Any string that appears immediately after one of the above three
1459           specifiers, and which is not itself a block name, renames the
1460           handlers exported by that preceding specifier by filtering each
1461           handler name through sprintf()
1462
1463       That is, you can specify handlers to be exported by exact name (as a
1464       string), by general pattern (as a regex), or collectively (in an
1465       array). And after any of these export specifications, you can append a
1466       template in which any '%s' will be replaced by the original name of the
1467       handler. For example:
1468
1469           # Selectively export specific sets of handlers...
1470           use Contextual::Return  qr/[NLR]VALUE/;
1471           use Contextual::Return  qr/.*REF/;
1472
1473           # Selective export specific sets and add a suffix to each...
1474           use Contextual::Return  qr/[NLR]VALUE/ => '%s_CONTEXT';
1475
1476           # Selective export specific sets and add a prefix to each...
1477           use Contextual::Return  qr/.*REF/ => 'CR_%s';
1478
1479           # Export a list of handlers...
1480           use Contextual::Return    'NUM', 'STR', 'BOOL' ;
1481           use Contextual::Return qw< NUM    STR    BOOL >;
1482           use Contextual::Return   ['NUM', 'STR', 'BOOL'];
1483
1484           # Export a list of handlers, renaming them individually...
1485           use Contextual::Return  NUM => 'NUMERIC', STR => 'TEXT', BOOL => 'CR_%s';
1486
1487           # Export a list of handlers, renaming them collectively...
1488           use Contextual::Return  ['NUM', 'STR', 'BOOL'] => '%s_CONTEXT';
1489
1490           # Mixed exports and renames...
1491           use Contextual::Return (
1492               STR => 'TEXT',
1493               ['NUM', 'BOOL'] => 'CR_%s',
1494               ['LIST', 'SCALAR', 'VOID', qr/^[NLR]VALUE/] => '%s_CONTEXT',
1495           );
1496

INTERFACE

1498   Context tests
1499       LIST()
1500           Returns true if the current subroutine was called in list context.
1501           A cleaner way of writing: wantarray()
1502
1503       SCALAR()
1504           Returns true if the current subroutine was called in scalar
1505           context.  A cleaner way of writing: "defined wantarray() && !
1506           wantarray()"
1507
1508       VOID()
1509           Returns true if the current subroutine was called in void context.
1510           A cleaner way of writing: "!defined wantarray()"
1511
1512       NONVOID()
1513           Returns true if the current subroutine was called in list or scalar
1514           context.  A cleaner way of writing: "defined wantarray()"
1515
1516   Standard contexts
1517       "LIST {...}"
1518           The block specifies what the context sequence should evaluate to
1519           when called in list context.
1520
1521       "SCALAR {...}"
1522           The block specifies what the context sequence should evaluate to in
1523           scalar contexts, unless some more-specific specifier scalar context
1524           specifier (see below) also occurs in the same context sequence.
1525
1526       "VOID {...}"
1527           The block specifies what the context sequence should do when called
1528           in void context.
1529
1530   Scalar value contexts
1531       "BOOL {...}"
1532           The block specifies what the context sequence should evaluate to
1533           when treated as a boolean value.
1534
1535       "NUM {...}"
1536           The block specifies what the context sequence should evaluate to
1537           when treated as a numeric value.
1538
1539       "STR {...}"
1540           The block specifies what the context sequence should evaluate to
1541           when treated as a string value.
1542
1543       "LAZY {...}"
1544           Another name for "SCALAR {...}". Usefully self-documenting when the
1545           primary purpose of the contextual return is to defer evaluation of
1546           the return value until it's actually required.
1547
1548   Scalar reference contexts
1549       "SCALARREF {...}"
1550           The block specifies what the context sequence should evaluate to
1551           when treated as a reference to a scalar.
1552
1553       "ARRAYREF {...}"
1554           The block specifies what the context sequence should evaluate to
1555           when treated as a reference to an array.
1556
1557       "HASHREF {...}"
1558           The block specifies what the context sequence should evaluate to
1559           when treated as a reference to a hash.
1560
1561           Note that a common error here is to write:
1562
1563           HASHREF { a=>1, b=>2, c=>3 }
1564
1565           The curly braces there are a block, not a hash constructor, so the
1566           block doesn't return a hash reference and the interpreter throws an
1567           exception.  What's needed is:
1568
1569           HASHREF { {a=>1, b=>2, c=>3} }
1570
1571           in which the inner braces are a hash constructor.
1572
1573       "CODEREF {...}"
1574           The block specifies what the context sequence should evaluate to
1575           when treated as a reference to a subroutine.
1576
1577       "GLOBREF {...}"
1578           The block specifies what the context sequence should evaluate to
1579           when treated as a reference to a typeglob.
1580
1581       "OBJREF {...}"
1582           The block specifies what the context sequence should evaluate to
1583           when treated as a reference to an object.
1584
1585       "METHOD {...}"
1586           The block can be used to specify particular handlers for specific
1587           method calls when the return value is treated as an object
1588           reference.  It should return a list of methodname/methodbody pairs.
1589           Each method name can be specified as a string, a regex, or an array
1590           of strings or regexes. The method bodies must be specified as
1591           subroutine references (usually anonymous subs). The first method
1592           name that matches the actual method call selects the corresponding
1593           handler, which is then called.
1594
1595   Generic contexts
1596       "VALUE {...}"
1597           The block specifies what the context sequence should evaluate to
1598           when treated as a non-referential value (as a boolean, numeric,
1599           string, scalar, or list). Only used if there is no more-specific
1600           value context specifier in the context sequence.
1601
1602       "REF {...}"
1603           The block specifies what the context sequence should evaluate to
1604           when treated as a reference of any kind. Only used if there is no
1605           more-specific referential context specifier in the context
1606           sequence.
1607
1608       "NONVOID {...}"
1609           The block specifies what the context sequence should evaluate to
1610           when used in a non-void context of any kind. Only used if there is
1611           no more-specific context specifier in the context sequence.
1612
1613       "DEFAULT {...}"
1614           The block specifies what the context sequence should evaluate to
1615           when used in a void or non-void context of any kind. Only used if
1616           there is no more-specific context specifier in the context
1617           sequence.
1618
1619   Failure context
1620       "FAIL"
1621           This block is executed unconditionally and is used to indicate
1622           failure. In a Boolean context it return false. In all other
1623           contexts it throws an exception consisting of the final evaluated
1624           value of the block.
1625
1626           That is, using "FAIL":
1627
1628           return FAIL { "Could not defenestrate the widget" }
1629
1630           is exactly equivalent to writing:
1631
1632           return BOOL { 0 } DEFAULT { croak "Could not defenestrate the
1633           widget" }
1634
1635           except that the reporting of errors is a little smarter under
1636           "FAIL".
1637
1638           If "FAIL" is called without specifying a block:
1639
1640           return FAIL;
1641
1642           it is equivalent to:
1643
1644           return FAIL { croak "Call to <subname> failed" }
1645
1646           (where "<subname>" is replaced with the name of the surrounding
1647           subroutine).
1648
1649           Note that, because "FAIL" implicitly covers every possible return
1650           context, it cannot be chained with other context specifiers.
1651
1652       "Contextual::Return::FAIL_WITH"
1653           This subroutine is not exported, but may be called directly to
1654           reconfigure "FAIL" behaviour in the caller's namespace.
1655
1656           The subroutine is called with an optional string (the flag),
1657           followed by a mandatory hash reference (the configurations hash),
1658           followed by a list of zero-or-more strings (the selector list). The
1659           values of the configurations hash must all be subroutine
1660           references.
1661
1662           If the optional flag is specified, "FAIL_WITH" searches the
1663           selector list looking for that string, then uses the following item
1664           in the selector list as its selector value. If that selector value
1665           is a string, "FAIL_WITH" looks up that key in the hash, and
1666           installs the corresponding subroutine as the namespace's "FAIL"
1667           handler (an exception is thrown if the selector string is not a
1668           valid key of the configurations hash). If the selector value is a
1669           subroutine reference, "FAIL_WITH" installs that subroutine as the
1670           "FAIL" handler.
1671
1672           If the optional flag is not specified, "FAIL_WITH" searches the
1673           entire selector list looking for the last element that matches any
1674           key in the configurations hash. It then looks up that key in the
1675           hash, and installs the corresponding subroutine as the namespace's
1676           "FAIL" handler.
1677
1678           See "Configurable failure contexts" for examples of using this
1679           feature.
1680
1681   Lvalue contexts
1682       "LVALUE"
1683           This block is executed when the result of an ":lvalue" subroutine
1684           is assigned to. The assigned value is passed to the block as $_. To
1685           access the caller's $_ value, use $CALLER::_.
1686
1687       "RVALUE"
1688           This block is executed when the result of an ":lvalue" subroutine
1689           is used as an rvalue. The final value that is evaluated in the
1690           block becomes the rvalue.
1691
1692       "NVALUE"
1693           This block is executed when an ":lvalue" subroutine is evaluated in
1694           void context.
1695
1696   Explicit result blocks
1697       "RESULT"
1698           This block may only appear inside a context handler block. It
1699           causes the surrounding handler to return the final value of the
1700           "RESULT"'s block, rather than the final value of the handler's own
1701           block. This override occurs regardless of the location to the
1702           "RESULT" block within the handler.
1703
1704           If called without a trailing "{...}", it simply returns the current
1705           result value in scalar contexts, or the list of result values in
1706           list context.
1707
1708   Recovery blocks
1709       "RECOVER"
1710           If present in a context return sequence, this block grabs control
1711           after any context handler returns or exits via an exception. If an
1712           exception was thrown it is passed to the "RECOVER" block via the $@
1713           variable.
1714
1715   Clean-up blocks
1716       "CLEANUP"
1717           If present in a context return sequence, this block grabs control
1718           when a return value is garbage collected.
1719
1720   Modifiers
1721       "FIXED"
1722           This specifies that the scalar value will only be evaluated once,
1723           the first time it is used, and that the value will then morph into
1724           that evaluated value.
1725
1726       "ACTIVE"
1727           This specifies that the scalar value's originating block will be
1728           re- evaluated every time the return value is used.
1729
1730   Debugging support
1731       "$crv->Contextual::Return::DUMP()"
1732           Return a dumpable representation of the return value in all viable
1733           contexts.
1734
1735       "local $Data::Dumper::Freezer = 'Contextual::Return::FREEZE';"
1736       "local $Data::Dumper::Freezer = \&Contextual::Return::FREEZE;"
1737           Configure Data::Dumper to correctly dump a representation of the
1738           contextual return value.
1739

DIAGNOSTICS

1741       "Can't use %s as export specifier"
1742           In your "use Contextual::Return" statement you specified something
1743           (such as a hash or coderef) that can't be used to select what the
1744           module exports. Make sure the list of selectors includes only
1745           strings, regexes, or references to arrays of strings or regexes.
1746
1747       "use Contextual::Return qr{%s} didn't export anything"
1748           In your "use Contextual::Return" statement you specified a regex to
1749           select which handlers to support, but the regex didn't select any
1750           handlers. Check that the regex you're using actually does match at
1751           least one of the names of the modules many handlers.
1752
1753       "Can't export %s: no such handler"
1754           In your "use Contextual::Return" statement you specified a string
1755           as the name of a context handler to be exported, but the module
1756           doesn't export a handler of that name. Check the spelling for the
1757           requested export.
1758
1759       "Can't call %s in a %s context"
1760       "Can't use return value of %s in a %s context"
1761           The subroutine you called uses a contextual return, but doesn't
1762           specify what to return in the particular context in which you
1763           called it. You either need to change the context in which you're
1764           calling the subroutine, or else add a context block corresponding
1765           to the offending context (or perhaps a "DEFAULT {...}" block).
1766
1767       "Can't call bare %s {...} in %s context"
1768           You specified a handler (such as "VOID {...}" or "LIST {...}")
1769           outside any subroutine, and in a context that it can't handle. Did
1770           you mean to place the handler outside of a subroutine?  If so, then
1771           you need to put it in a context it can actually handle.  Otherwise,
1772           perhaps you need to replace the trailing block with parens (that
1773           is: VOID() or LIST()).
1774
1775       "Call to %s at %s didn't return a %s reference""
1776           You called the subroutine in a context that expected to get back a
1777           reference of some kind but the subroutine didn't specify the
1778           corresponding "SCALARREF", "ARRAYREF", "HASHREF", "CODEREF",
1779           "GLOBREF", or generic "REF", "NONVOID", or "DEFAULT" handlers.  You
1780           need to specify the appropriate one of these handlers in the
1781           subroutine.
1782
1783       "Can't call method '%s' on %s value returned by %s""
1784           You called the subroutine and then tried to call a method on the
1785           return value, but the subroutine returned a classname or object
1786           that doesn't have that method. This probably means that the
1787           subroutine didn't return the classname or object you expected. Or
1788           perhaps you need to specify an "OBJREF {...}" context block.
1789
1790       "Can't install two %s handlers"
1791           You attempted to specify two context blocks of the same name in the
1792           same return context, which is ambiguous. For example:
1793
1794               sub foo: lvalue {
1795                   LVALUE { $foo = $_ }
1796                   RVALUE { $foo }
1797                   LVALUE { $foo = substr($_,1,10) }
1798               }
1799
1800           or:
1801
1802               sub bar {
1803                   return
1804                       BOOL { 0 }
1805                       NUM  { 1 }
1806                       STR  { "two" }
1807                       BOOL { 1 };
1808               }
1809
1810           Did you cut-and-paste wrongly, or mislabel one of the blocks?
1811
1812       "Expected a %s block after the %s block but found instead: %s"
1813           If you specify any of "LVALUE", "RVALUE", or "NVALUE", then you can
1814           only specify "LVALUE", "RVALUE", or "NVALUE" blocks in the same
1815           return context.  If you need to specify other contexts (like
1816           "BOOL", or "STR", or "REF", etc.), put them inside an "RVALUE"
1817           block. See "Lvalue contexts" for an example.
1818
1819       "Call to %s failed at %s"
1820           This is the default exception that a "FAIL" throws in a non-scalar
1821           context. Which means that the subroutine you called has signalled
1822           failure by throwing an exception, and you didn't catch that
1823           exception.  You should either put the call in an "eval {...}" block
1824           or else call the subroutine in boolean context instead.
1825
1826       "Call to %s failed at %s. Attempted to use failure value at %s"
1827           This is the default exception that a "FAIL" throws when a failure
1828           value is captured in a scalar variable and later used in a non-
1829           boolean context. That means that the subroutine you called must
1830           have failed, and you didn't check the return value for that
1831           failure, so when you tried to use that invalid value it killed your
1832           program. You should either put the original call in an "eval {...}"
1833           or else test the return value in a boolean context and avoid using
1834           it if it's false.
1835
1836       "Usage: FAIL_WITH $flag_opt, \%selector, @args"
1837           The "FAIL_WITH" subroutine expects an optional flag, followed by a
1838           reference to a configuration hash, followed by a list or selector
1839           arguments. You gave it something else. See "Configurable Failure
1840           Contexts".
1841
1842       "Selector values must be sub refs"
1843           You passed a configuration hash to "FAIL_WITH" that specified non-
1844           subroutines as possible "FAIL" handlers. Since non-subroutines
1845           can't possibly be handlers, maybe you forgot the "sub" keyword
1846           somewhere?
1847
1848       "Invalid option: %s =" %s>
1849           The "FAIL_WITH" subroutine was passed a flag/selector pair, but the
1850           selector was not one of those allowed by the configuration hash.
1851
1852       "FAIL handler for package %s redefined"
1853           A warning that the "FAIL" handler for a particular package was
1854           reconfigured more than once. Typically that's because the module
1855           was loaded in two places with difference configurations specified.
1856           You can't reasonably expect two different sets of behaviours from
1857           the one module within the one namespace.
1858

CONFIGURATION AND ENVIRONMENT

1860       Contextual::Return requires no configuration files or environment
1861       variables.
1862

DEPENDENCIES

1864       Requires version.pm and Want.pm.
1865

INCOMPATIBILITIES

1867       "LVALUE", "RVALUE", and "NVALUE" do not work correctly under the Perl
1868       debugger. This seems to be because the debugger injects code to capture
1869       the return values from subroutines, which interferes destructively with
1870       the optional final arguments that allow "LVALUE", "RVALUE", and
1871       "NVALUE" to cascade within a single return.
1872

BUGS AND LIMITATIONS

1874       No bugs have been reported.
1875

AUTHOR

1877       Damian Conway  "<DCONWAY@cpan.org>"
1878
1880       Copyright (c) 2005-2011, Damian Conway "<DCONWAY@cpan.org>". All rights
1881       reserved.
1882
1883       This module is free software; you can redistribute it and/or modify it
1884       under the same terms as Perl itself.
1885

DISCLAIMER OF WARRANTY

1887       BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
1888       FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT
1889       WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER
1890       PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND,
1891       EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1892       WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
1893       ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
1894       YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
1895       NECESSARY SERVICING, REPAIR, OR CORRECTION.
1896
1897       IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
1898       WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
1899       REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE
1900       TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR
1901       CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
1902       SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
1903       RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
1904       FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
1905       SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
1906       DAMAGES.
1907
1908
1909
1910perl v5.36.0                      2023-01-20             Contextual::Return(3)
Impressum