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

NAME

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

VERSION

9       This document describes Contextual::Return version 0.2.1
10

SYNOPSIS

12           use Contextual::Return;
13           use Carp;
14
15           sub foo {
16               return
17                   SCALAR { 'thirty-twelve' }
18                   BOOL   { 1 }
19                   NUM    { 7*6 }
20                   STR    { 'forty-two' }
21
22                   LIST   { 1,2,3 }
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
75       when 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 three extra
215       context blocks: "BOOL", "NUM", and "STR":
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                      BOOL { $server_data{uptime} > 0                    }
228                       NUM { $server_data{load}                          }
229                       STR { "$server_data{name}: $server_data{uptime}"  }
230                      VOID { print "$server_data{load}\n"                }
231                   DEFAULT { croak q{Bad context! No biscuit!}           }
232               );
233           }
234
235       With these in place, the object returned from a scalar-context call to
236       "get_server_status()" now behaves differently, depending on how it's
237       used. For example:
238
239           if ( my $status = get_server_status() ) {  # True if uptime > 0
240               $load_distribution[$status]++;         # Evaluates to load value
241               print "$status\n";                     # Prints name: uptime
242           }
243
244   Referential contexts
245       The other major kind of scalar return value is a reference.
246       Contextual::Return provides contextual return blocks that allow you to
247       specify what to (lazily) return when the return value of a subroutine
248       is used as a reference to a scalar ("SCALARREF {...}"), to an array
249       ("ARRAYREF {...}"), to a hash ("HASHREF {...}"), to a subroutine
250       ("CODEREF {...}"), or to a typeglob ("GLOBREF {...}").
251
252       For example, the server status subroutine shown earlier could be
253       extended to allow it to return a hash reference, thereby supporting
254       "named return values":
255
256           sub get_server_status {
257               my ($server_ID) = @_;
258
259               # Acquire server data somehow...
260               my %server_data = _ascertain_server_status($server_ID);
261
262               # Return different components of that data
263               # depending on call context...
264               return (
265                      LIST { @server_data{ qw(name uptime load users) }  }
266                      BOOL { $server_data{uptime} > 0                    }
267                       NUM { $server_data{load}                          }
268                       STR { "$server_data{name}: $server_data{uptime}"  }
269                      VOID { print "$server_data{load}\n"                }
270                   HASHREF { return \%server_data                        }
271                   DEFAULT { croak q{Bad context! No biscuit!}           }
272               );
273           }
274
275           # and later...
276
277           my $users = get_server_status->{users};
278
279
280           # or, lazily...
281
282           my $server = get_server_status();
283
284           print "$server->{name} load = $server->{load}\n";
285
286   Interpolative referential contexts
287       The "SCALARREF {...}" and "ARRAYREF {...}" context blocks are
288       especially useful when you need to interpolate a subroutine into
289       strings. For example, if you have a subroutine like:
290
291           sub get_todo_tasks {
292               return (
293                   SCALAR { scalar @todo_list }      # How many?
294                   LIST   { @todo_list        }      # What are they?
295               );
296           }
297
298           # and later...
299
300           print "There are ", scalar(get_todo_tasks()), " tasks:\n",
301                 get_todo_tasks();
302
303       then you could make it much easier to interpolate calls to that
304       subroutine by adding:
305
306           sub get_todo_tasks {
307               return (
308                   SCALAR { scalar @todo_list }      # How many?
309                   LIST   { @todo_list        }      # What are they?
310
311                   SCALARREF { \scalar @todo_list }  # Ref to how many
312                   ARRAYREF  { \@todo_list        }  # Ref to them
313               );
314           }
315
316           # and then...
317
318           print "There are ${get_todo_tasks()} tasks:\n@{get_todo_tasks()}";
319
320       In fact, this behaviour is so useful that it's the default. If you
321       don't provide an explicit "SCALARREF {...}" block, Contextual::Return
322       automatically provides an implicit one that simply returns a reference
323       to whatever would have been returned in scalar context.  Likewise, if
324       no "ARRAYREF {...}" block is specified, the module supplies one that
325       returns the list-context return value wrapped up in an array reference.
326
327       So you could just write:
328
329           sub get_todo_tasks {
330               return (
331                   SCALAR { scalar @todo_list }      # How many?
332                   LIST   { @todo_list        }      # What are they?
333               );
334           }
335
336           # and still do this...
337
338           print "There are ${get_todo_tasks()} tasks:\n@{get_todo_tasks()}";
339
340   Fallback contexts
341       As the previous sections imply, the "BOOL {...}", "NUM {...}", "STR
342       {...}", and various "*REF {...}" blocks, are special cases of the
343       general "SCALAR {...}" context block. If a subroutine is called in one
344       of these specialized contexts but does not use the corresponding
345       context block, then the more general "SCALAR {...}" block is used
346       instead (if it has been specified).
347
348       So, for example:
349
350           sub read_value_from {
351               my ($fh) = @_;
352
353               my $value = <$fh>;
354               chomp $value;
355
356               return (
357                   BOOL   { defined $value }
358                   SCALAR { $value         }
359               );
360           }
361
362       ensures that the "read_value_from()" subroutine returns true in boolean
363       contexts if the read was successful. But, because no specific "NUM
364       {...}" or "STR {...}" return behaviours were specified, the subroutine
365       falls back on using its generic "SCALAR {...}" block in all other
366       scalar contexts.
367
368       Another way to think about this behaviour is that the various kinds of
369       scalar context blocks form a hierarchy:
370
371           SCALAR
372              ^
373              |
374              |--< BOOL
375              |
376              |--< NUM
377              |
378              `--< STR
379
380       Contextual::Return uses this hierarchical relationship to choose the
381       most specific context block available to handle any particular return
382       context, working its way up the tree from the specific type it needs,
383       to the more general type, if that's all that is available.
384
385       There are two slight complications to this picture. The first is that
386       Perl treats strings and numbers as interconvertable so the diagram (and
387       the Contextual::Return module) also has to allow these interconversions
388       as a fallback strategy:
389
390           SCALAR
391              ^
392              |
393              |--< BOOL
394              |
395              |--< NUM
396              |    : ^
397              |    v :
398              `--< STR
399
400       The dotted lines are meant to indicate that this intraconversion is
401       secondary to the main hierarchical fallback. That is, in a numeric
402       context, a "STR {...}" block will only be used if there is no "NUM
403       {...}" block and no "SCALAR {...}" block. In other words, the generic
404       context type is always used in preference to string<->number
405       conversion.
406
407       The second slight complication is that the above diagram only shows a
408       small part of the complete hierarchy of contexts supported by
409       Contextual::Return. The full fallback hierarchy (including dotted
410       interconversions) is:
411
412           DEFAULT
413              ^
414              |
415              |--< VOID
416              |
417              `--< NONVOID
418                      ^
419                      |
420                      |--< VALUE <..............
421                      |      ^                 :
422                      |      |                 :
423                      |      |--< SCALAR <.....:..
424                      |      |       ^           :
425                      |      |       |           :
426                      |      |       |--< BOOL   :
427                      |      |       |           :
428                      |      |       |--< NUM <..:..
429                      |      |       |    : ^      :
430                      |      |       |    v :      :
431                      |      |       `--< STR <....:..
432                      |      |                       :
433                      |      |                      .:
434                      |      `--< LIST ............. :
435                      |            : ^               :
436                      |            : :               :
437                      `--- REF     : :               :
438                            ^      : :               :
439                            |      v :               :
440                            |--< ARRAYREF            :
441                            |                       .
442                            |--< SCALARREF .........
443                            |
444                            |--< HASHREF
445                            |
446                            |--< CODEREF
447                            |
448                            |--< GLOBREF
449                            |
450                            `--< OBJREF
451
452       As before, each dashed arrow represents a fallback relationship. That
453       is, if the required context specifier isn't available, the arrows are
454       followed until a more generic one is found. The dotted arrows again
455       represent the interconversion of return values, which is attempted only
456       after the normal hierarchical fallback fails.
457
458       For example, if a subroutine is called in a context that expects a
459       scalar reference, but no "SCALARREF {...}" block is provided, then
460       Contextual::Return tries the following blocks in order:
461
462               REF {...}
463           NONVOID {...}
464           DEFAULT {...}
465               STR {...} (automatically taking a reference to the result)
466               NUM {...} (automatically taking a reference to the result)
467            SCALAR {...} (automatically taking a reference to the result)
468             VALUE {...} (automatically taking a reference to the result)
469
470       Likewise, in a list context, if there is no "LIST {...}" context block,
471       the module tries:
472
473              VALUE {...}
474            NONVOID {...}
475            DEFAULT {...}
476           ARRAYREF {...} (automatically dereferencing the result)
477                STR {...} (treating it as a list of one element)
478                NUM {...} (treating it as a list of one element)
479             SCALAR {...} (treating it as a list of one element)
480              VALUE {...} (treating it as a list of one element)
481
482       The more generic context blocks are especially useful for intercepting
483       unexpected and undesirable call contexts. For example, to turn off the
484       automatic scalar-ref and array-ref interpolative behaviour described in
485       "Interpolative referential contexts", you could intercept all
486       referential contexts using a generic "REF {...}" context block:
487
488           sub get_todo_tasks {
489               return (
490                   SCALAR { scalar @todo_list }      # How many?
491                   LIST   { @todo_list        }      # What are they?
492
493                   REF { croak q{get_todo_task() can't be used as a reference} }
494               );
495           }
496
497           print 'There are ', get_todo_tasks(), '...';    # Still okay
498           print "There are ${get_todo_tasks()}...";       # Throws an exception
499
500   Failure contexts
501       Two of the most common ways to specify that a subroutine has failed are
502       to return a false value, or to throw an exception. The
503       Contextual::Return module provides a mechanism that allows the
504       subroutine writer to support both of these mechanisms at the same time,
505       by using the "FAIL" specifier.
506
507       A return statement of the form:
508
509           return FAIL;
510
511       causes the surrounding subroutine to return "undef" (i.e. false) in
512       boolean contexts, and to throw an exception in any other context. For
513       example:
514
515           use Contextual::Return;
516
517           sub get_next_val {
518               my $next_val = <>;
519               return FAIL if !defined $next_val;
520               chomp $next_val;
521               return $next_val;
522           }
523
524       If the "return FAIL" statement is executed, it will either return false
525       in a boolean context:
526
527           if (my $val = get_next_val()) {    # returns undef if no next val
528               print "[$val]\n";
529           }
530
531       or else throw an exception if the return value is used in any other
532       context:
533
534           print get_next_val();       # throws exception if no next val
535
536           my $next_val = get_next_val();
537           print "[$next_val]\n";      # throws exception if no next val
538
539       The exception that is thrown is of the form:
540
541           Call to main::get_next_val() failed at demo.pl line 42
542
543       but you can change that message by providing a block to the "FAIL",
544       like so:
545
546           return FAIL { "No more data" } if !defined $next_val;
547
548       in which case, the final value of the block becomes the exception
549       message:
550
551           No more data at demo.pl line 42
552
553   Configurable failure contexts
554       The default "FAIL" behaviour--false in boolean context, fatal in all
555       others--works well in most situations, but violates the Platinum Rule
556       ("Do unto others as they would have done unto them").
557
558       So it may be user-friendlier if the user of a module is allowed decide
559       how the module's subroutines should behave on failure. For example, one
560       user might prefer that failing subs always return undef; another might
561       prefer that they always throw an exception; a third might prefer that
562       they always log the problem and return a special Failure object; whilst
563       a fourth user might want to get back 0 in scalar contexts, an empty
564       list in list contexts, and an exception everywhere else.
565
566       You could create a module that allows the user to specify all these
567       alternatives, like so:
568
569           package MyModule;
570           use Contextual::Return;
571           use Log::StdLog;
572
573           sub import {
574               my ($package, @args) = @_;
575
576               Contextual::Return::FAIL_WITH {
577                   ':false' => sub { return undef },
578                   ':fatal' => sub { croak @_     },
579                   ':filed' => sub {
580                                   print STDLOG 'Sub ', (caller 1)[3], ' failed';
581                                   return Failure->new();
582                               },
583                   ':fussy' => sub {
584                                   SCALAR  { undef    }
585                                   LIST    { ()       }
586                                   DEFAULT { croak @_ }
587                               },
588               }, @args;
589           }
590
591       This configures Contextual::Return so that, instead of the usual false-
592       or-fatal semantics, every "return FAIL" within MyModule's namespace is
593       implemented by one of the four subroutines specified in the hash that
594       was passed to "FAIL_WITH".
595
596       Which of those four subs implements the "FAIL" is determined by the
597       arguments passed after the hash (i.e. by the contents of @args).
598       "FAIL_WITH" walks through that list of arguments and compares them
599       against the keys of the hash. If a key matches an argument, the
600       corresponding value is used as the implementation of "FAIL". Note that,
601       if subsequent arguments also match a key, their subroutine overrides
602       the previously installed implementation, so only the final override has
603       any effect. Contextual::Return generates warnings when multiple
604       overrides are specified.
605
606       All of which mean that, if a user loaded the MyModule module like this:
607
608           use MyModule qw( :fatal other args here );
609
610       then every "FAIL" within MyModule would be reconfigured to throw an
611       exception in all circumstances, since the presence of the ':fatal' in
612       the argument list will cause "FAIL_WITH" to select the hash entry whose
613       key is ':fatal'.
614
615       On the other hand, if they loaded the module:
616
617           use MyModule qw( :fussy other args here );
618
619       then each "FAIL" within MyModule would return undef or empty list or
620       throw an exception, depending on context, since that's what the
621       subroutine whose key is ':fussy' does.
622
623       Many people prefer module interfaces with a "flag =" value> format, and
624       "FAIL_WITH" supports this too. For example, if you wanted your module
625       to take a "-fail" flag, whose associated value could be any of
626       "undefined", "exception", "logged", or "context", then you could
627       implement that simply by specifying the flag as the first argument
628       (i.e. before the hash) like so:
629
630           sub import {
631               my $package = shift;
632
633               Contextual::Return::FAIL_WITH -fail => {
634                   'undefined' => sub { return undef },
635                   'exception' => sub { croak @_     },
636                   'logged'    => sub {
637                                   print STDLOG 'Sub ', (caller 1)[3], ' failed';
638                                   return Failure->new();
639                               },
640                   'context'   => sub {
641                                   SCALAR  { undef    }
642                                   LIST    { ()       }
643                                   DEFAULT { croak @_ }
644                               },
645               }, @_;
646
647       and then load the module:
648
649           use MyModule qw( other args here ), -fail=>'undefined';
650
651       or:
652
653           use MyModule qw( other args here ), -fail=>'exception';
654
655       In this case, "FAIL_WITH" scans the argument list for a pair of values:
656       its flag string, followed by some other selector value. Then it looks
657       up the selector value in the hash, and installs the corresponding
658       subroutine as its local "FAIL" handler.
659
660       If this "flagged" interface is used, the user of the module can also
661       specify their own handler directly, by passing a subroutine reference
662       as the selector value instead of a string:
663
664           use MyModule qw( other args here ), -fail=>sub{ die 'horribly'};
665
666       If this last example were used, any call to "FAIL" within MyModule
667       would invoke the specified anonymous subroutine (and hence throw a
668       'horribly' exception).
669
670       Note that, any overriding of a "FAIL" handler is specific to the
671       namespace and file from which the subroutine that calls "FAIL_WITH" is
672       itself called. Since "FAIL_WITH" is designed to be called from within a
673       module's "import()" subroutine, that generally means that the "FAIL"s
674       within a given module X are only overridden for the current namespace
675       within the particular file from module X is loaded. This means that two
676       separate pieces of code (in separate files or separate namespaces) can
677       each independently overide a module's "FAIL" behaviour, without
678       interfering with each other.
679
680   Lvalue contexts
681       Recent versions of Perl offer (limited) support for lvalue subroutines:
682       subroutines that return a modifiable variable, rather than a simple
683       constant value.
684
685       Contextual::Return can make it easier to create such subroutines,
686       within the limitations imposed by Perl itself. The limitations that
687       Perl places on lvalue subs are:
688
689       1.  The subroutine must be declared with an ":lvalue" attribute:
690
691               sub foo :lvalue {...}
692
693       2.  The subroutine must not return via an explicit "return". Instead,
694           the last statement must evaluate to a variable, or must be a call
695           to another lvalue subroutine call.
696
697               my ($foo, $baz);
698
699               sub foo :lvalue {
700                   $foo;               # last statement evals to a var
701               }
702
703               sub bar :lvalue {
704                   foo();              # last statement is lvalue sub call
705               }
706
707               sub baz :lvalue {
708                   my ($arg) = @_;
709
710                   $arg > 0            # last statement evals...
711                       ? $baz          #   ...to a var
712                       : bar();        #   ...or to an lvalue sub call
713               }
714
715       Thereafter, any call to the lvalue subroutine produces a result that
716       can be assigned to:
717
718           baz(0) = 42;            # same as: $baz = 42
719
720           baz(1) = 84;            # same as:                bar() = 84
721                                   #  which is the same as:  foo() = 84
722                                   #   which is the same as: $foo  = 84
723
724       Ultimately, every lvalue subroutine must return a scalar variable,
725       which is then used as the lvalue of the assignment (or whatever other
726       lvalue operation is applied to the subroutine call). Unfortunately,
727       because the subroutine has to return this variable before the
728       assignment can take place, there is no way that a normal lvalue
729       subroutine can get access to the value that will eventually be assigned
730       to its return value.
731
732       This is occasionally annoying, so the Contextual::Return module offers
733       a solution: in addition to all the context blocks described above, it
734       provides three special contextual return blocks specifically for use in
735       lvalue subroutines: "LVALUE", "RVALUE", and "NVALUE".
736
737       Using these blocks you can specify what happens when an lvalue
738       subroutine is used in lvalue and non-lvalue (rvalue) context. For
739       example:
740
741           my $verbosity_level = 1;
742
743           # Verbosity values must be between 0 and 5...
744           sub verbosity :lvalue {
745               LVALUE { $verbosity_level = max(0, min($_, 5)) }
746               RVALUE { $verbosity_level                      }
747           }
748
749       The "LVALUE" block is executed whenever "verbosity" is called as an
750       lvalue:
751
752           verbosity() = 7;
753
754       The block has access to the value being assigned, which is passed to it
755       as $_. So, in the above example, the assigned value of 7 would be
756       aliased to $_ within the "LVALUE" block, would be reduced to 5 by the
757       "min-of-max" expression, and then assigned to $verbosity_level.
758
759       (If you need to access the caller's $_, it's also still available: as
760       $CALLER::_.)
761
762       When the subroutine isn't used as an lvalue:
763
764           print verbosity();
765
766       the "RVALUE" block is executed instead and its final value returned.
767       Within an "RVALUE" block you can use any of the other features of
768       Contextual::Return. For example:
769
770           sub verbosity :lvalue {
771               LVALUE { $verbosity_level = int max(0, min($_, 5)) }
772               RVALUE {
773                   NUM  { $verbosity_level               }
774                   STR  { $description[$verbosity_level] }
775                   BOOL { $verbosity_level > 2           }
776               }
777           }
778
779       but the context sequence must be nested inside an "RVALUE" block.
780
781       You can also specify what an lvalue subroutine should do when it is
782       used neither as an lvalue nor as an rvalue (i.e. in void context), by
783       using an "NVALUE" block:
784
785           sub verbosity :lvalue {
786               my ($level) = @_;
787
788               NVALUE { $verbosity_level = int max(0, min($level, 5)) }
789               LVALUE { $verbosity_level = int max(0, min($_,     5)) }
790               RVALUE {
791                   NUM  { $verbosity_level               }
792                   STR  { $description[$verbosity_level] }
793                   BOOL { $verbosity_level > 2           }
794               }
795           }
796
797       In this example, a call to "verbosity()" in void context sets the
798       verbosity level to whatever argument is passed to the subroutine:
799
800           verbosity(1);
801
802       Note that you cannot get the same effect by nesting a "VOID" block
803       within an "RVALUE" block:
804
805               LVALUE { $verbosity_level = int max(0, min($_, 5)) }
806               RVALUE {
807                   NUM  { $verbosity_level               }
808                   STR  { $description[$verbosity_level] }
809                   BOOL { $verbosity_level > 2           }
810                   VOID { $verbosity_level = $level      }    # Wrong!
811               }
812
813       That's because, in a void context the return value is never evaluated,
814       so it is never treated as an rvalue, which means the "RVALUE" block
815       never executes.
816
817   Result blocks
818       Occasionally, it's convenient to calculate a return value before the
819       end of a contextual return block. For example, you may need to clean up
820       external resources involved in the calculation after it's complete.
821       Typically, this requirement produces a slightly awkward code sequence
822       like this:
823
824           return
825               VALUE {
826                   $db->start_work();
827                   my $result = $db->retrieve_query($query);
828                   $db->commit();
829                   $result;
830               }
831
832       Such code sequences become considerably more awkward when you want the
833       return value to be context sensitive, in which case you have to write
834       either:
835
836           return
837               LIST {
838                   $db->start_work();
839                   my @result = $db->retrieve_query($query);
840                   $db->commit();
841                   @result;
842               }
843               SCALAR {
844                   $db->start_work();
845                   my $result = $db->retrieve_query($query);
846                   $db->commit();
847                   $result;
848               }
849
850       or, worse:
851
852           return
853               VALUE {
854                   $db->start_work();
855                   my $result = LIST ? [$db->retrieve_query($query)]
856                                     :  $db->retrieve_query($query);
857                   $db->commit();
858                   LIST ? @{$result} : $result;
859               }
860
861       To avoid these infelicities, Contextual::Return provides a second way
862       of setting the result of a context block; a way that doesn't require
863       that the result be the last statement in the block:
864
865           return
866               LIST {
867                   $db->start_work();
868                   RESULT { $db->retrieve_query($query) };
869                   $db->commit();
870               }
871               SCALAR {
872                   $db->start_work();
873                   RESULT { $db->retrieve_query($query) };
874                   $db->commit();
875               }
876
877       The presence of a "RESULT" block inside a contextual return block
878       causes that block to return the value of the final statement of the
879       "RESULT" block as the handler's return value, rather than returning the
880       value of the handler's own final statement. In other words, the
881       presence of a "RESULT" block overrides the normal return value of a
882       context handler.
883
884       Better still, the "RESULT" block always evaluates its final statement
885       in the same context as the surrounding "return", so you can just write:
886
887           return
888               VALUE {
889                   $db->start_work();
890                   RESULT { $db->retrieve_query($query) };
891                   $db->commit();
892               }
893
894       and the "retrieve_query()" method will be called in the appropriate
895       context in all cases.
896
897       A "RESULT" block can appear anywhere inside any contextual return
898       block, but may not be used outside a context block. That is, this is an
899       error:
900
901           if ($db->closed) {
902               RESULT { undef };   # Error: not in a context block
903           }
904           return
905               VALUE {
906                   $db->start_work();
907                   RESULT { $db->retrieve_query($query) };
908                   $db->commit();
909               }
910
911   Post-handler clean-up
912       If a subroutine uses an external resource, it's often necessary to
913       close or clean-up that resource after the subroutine ends...regardless
914       of whether the subroutine exits normally or via an exception.
915
916       Typically, this is done by encapsulating the resource in a lexically
917       scoped object whose constructor does the clean-up. However, if the
918       clean-up doesn't involve deallocation of an object (as in the
919       "$db->commit()" example in the previous section), it can be annoying to
920       have to create a class and allocate a container object, merely to
921       mediate the clean-up.
922
923       To make it easier to manage such resources, Contextual::Return supplies
924       a special labelled block: the "RECOVER" block. If a "RECOVER" block is
925       specified as part of a contextual return sequence, that block is
926       executed after any context handler, even if the context handler exits
927       via an exception.
928
929       So, for example, you could implement a simple commit-or-revert policy
930       like so:
931
932           return
933               LIST    { $db->retrieve_all($query) }
934               SCALAR  { $db->retrieve_next($query) }
935               RECOVER {
936                   if ($@) {
937                       $db->revert();
938                   }
939                   else {
940                       $db->commit();
941                   }
942               }
943
944       The presence of a "RECOVER" block also intercepts all exceptions thrown
945       in any other context block in the same contextual return sequence. Any
946       such exception is passed into the "RECOVER" block in the usual manner:
947       via the $@ variable. The exception may be rethrown out of the "RECOVER"
948       block by calling "die":
949
950           return
951               LIST    { $db->retrieve_all($query) }
952               DEFAULT { croak "Invalid call (not in list context)" }
953               RECOVER {
954                   die $@ if $@;    # Propagate any exception
955                   $db->commit();   # Otherwise commit the changes
956               }
957
958       A "RECOVER" block can also access or replace the returned value, by
959       invoking a "RESULT" block. For example:
960
961           return
962               LIST    { attempt_to_generate_list_for(@_)  }
963               SCALAR  { attempt_to_generate_count_for(@_) }
964               RECOVER {
965                   if ($@) {                # On any exception...
966                       RESULT { undef }     # ...return undef
967                   }
968               }
969

INTERFACE

971   Context tests
972       "LIST()"
973           Returns true if the current subroutine was called in list context.
974           A cleaner way of writing: "wantarray()"
975
976       "SCALAR()"
977           Returns true if the current subroutine was called in scalar
978           context.  A cleaner way of writing: "defined wantarray() && !
979           wantarray()"
980
981       "VOID()"
982           Returns true if the current subroutine was called in void context.
983           A cleaner way of writing: "!defined wantarray()"
984
985       "NONVOID()"
986           Returns true if the current subroutine was called in list or scalar
987           context.  A cleaner way of writing: "defined wantarray()"
988
989   Standard contexts
990       "LIST {...}"
991           The block specifies what the context sequence should evaluate to
992           when called in list context.
993
994       "SCALAR {...}"
995           The block specifies what the context sequence should evaluate to in
996           scalar contexts, unless some more-specific specifier scalar context
997           specifier (see below) also occurs in the same context sequence.
998
999       "VOID {...}"
1000           The block specifies what the context sequence should do when called
1001           in void context.
1002
1003   Scalar value contexts
1004       "BOOL {...}"
1005           The block specifies what the context sequence should evaluate to
1006           when treated as a boolean value.
1007
1008       "NUM {...}"
1009           The block specifies what the context sequence should evaluate to
1010           when treated as a numeric value.
1011
1012       "STR {...}"
1013           The block specifies what the context sequence should evaluate to
1014           when treated as a string value.
1015
1016       "LAZY {...}"
1017           Another name for "SCALAR {...}". Usefully self-documenting when the
1018           primary purpose of the contextual return is to defer evaluation of
1019           the return value until it's actually required.
1020
1021   Scalar reference contexts
1022       "SCALARREF {...}"
1023           The block specifies what the context sequence should evaluate to
1024           when treated as a reference to a scalar.
1025
1026       "ARRAYREF {...}"
1027           The block specifies what the context sequence should evaluate to
1028           when treated as a reference to an array.
1029
1030       "HASHREF {...}"
1031           The block specifies what the context sequence should evaluate to
1032           when treated as a reference to a hash.
1033
1034           Note that a common error here is to write:
1035
1036               HASHREF { a=>1, b=>2, c=>3 }
1037
1038           The curly braces there are a block, not a hash constructor, so the
1039           block doesn't return a hash reference and the interpreter throws an
1040           exception.  What's needed is:
1041
1042               HASHREF { {a=>1, b=>2, c=>3} }
1043
1044           in which the inner braces are a hash constructor.
1045
1046       "CODEREF {...}"
1047           The block specifies what the context sequence should evaluate to
1048           when treated as a reference to a subroutine.
1049
1050       "GLOBREF {...}"
1051           The block specifies what the context sequence should evaluate to
1052           when treated as a reference to a typeglob.
1053
1054       "OBJREF {...}"
1055           The block specifies what the context sequence should evaluate to
1056           when treated as a reference to an object.
1057
1058   Generic contexts
1059       "VALUE {...}"
1060           The block specifies what the context sequence should evaluate to
1061           when treated as a non-referential value (as a boolean, numeric,
1062           string, scalar, or list). Only used if there is no more-specific
1063           value context specifier in the context sequence.
1064
1065       "REF {...}"
1066           The block specifies what the context sequence should evaluate to
1067           when treated as a reference of any kind. Only used if there is no
1068           more-specific referential context specifier in the context
1069           sequence.
1070
1071       "NONVOID {...}"
1072           The block specifies what the context sequence should evaluate to
1073           when used in a non-void context of any kind. Only used if there is
1074           no more-specific context specifier in the context sequence.
1075
1076       "DEFAULT {...}"
1077           The block specifies what the context sequence should evaluate to
1078           when used in a void or non-void context of any kind. Only used if
1079           there is no more-specific context specifier in the context
1080           sequence.
1081
1082   Failure context
1083       "FAIL"
1084           This block is executed unconditionally and is used to indicate
1085           failure. In a Boolean context it return false. In all other
1086           contexts it throws an exception consisting of the final evaluated
1087           value of the block.
1088
1089           That is, using "FAIL":
1090
1091               return
1092                   FAIL { "Could not defenestrate the widget" }
1093
1094           is exactly equivalent to writing:
1095
1096               return
1097                      BOOL { 0 }
1098                   DEFAULT { croak "Could not defenestrate the widget" }
1099
1100           except that the reporting of errors is a little smarter under
1101           "FAIL".
1102
1103           If "FAIL" is called without specifying a block:
1104
1105               return FAIL;
1106
1107           it is equivalent to:
1108
1109               return FAIL { croak "Call to <subname> failed" }
1110
1111           (where "<subname>" is replaced with the name of the surrounding
1112           subroutine).
1113
1114           Note that, because "FAIL" implicitly covers every possible return
1115           context, it cannot be chained with other context specifiers.
1116
1117       "Contextual::Return::FAIL_WITH"
1118           This subroutine is not exported, but may be called directly to
1119           reconfigure "FAIL" behaviour in the caller's namespace.
1120
1121           The subroutine is called with an optional string (the flag),
1122           followed by a mandatory hash reference (the configurations hash),
1123           followed by a list of zero-or-more strings (the selector list). The
1124           values of the configurations hash must all be subroutine
1125           references.
1126
1127           If the optional flag is specified, "FAIL_WITH" searches the
1128           selector list looking for that string, then uses the following item
1129           in the selector list as its selector value. If that selector value
1130           is a string, "FAIL_WITH" looks up that key in the hash, and
1131           installs the corresponding subroutine as the namespace's "FAIL"
1132           handler (an exception is thrown if the selector string is not a
1133           valid key of the configurations hash). If the selector value is a
1134           subroutine reference, "FAIL_WITH" installs that subroutine as the
1135           "FAIL" handler.
1136
1137           If the optional flag is not specified, "FAIL_WITH" searches the
1138           entire selector list looking for the last element that matches any
1139           key in the configurations hash. It then looks up that key in the
1140           hash, and installs the corresponding subroutine as the namespace's
1141           "FAIL" handler.
1142
1143           See "Configurable failure contexts" for examples of using this
1144           feature.
1145
1146   Lvalue contexts
1147       "LVALUE"
1148           This block is executed when the result of an ":lvalue" subroutine
1149           is assigned to. The assigned value is passed to the block as $_. To
1150           access the caller's $_ value, use $CALLER::_.
1151
1152       "RVALUE"
1153           This block is executed when the result of an ":lvalue" subroutine
1154           is used as an rvalue. The final value that is evaluated in the
1155           block becomes the rvalue.
1156
1157       "NVALUE"
1158           This block is executed when an ":lvalue" subroutine is evaluated in
1159           void context.
1160
1161   Explicit result blocks
1162       "RESULT"
1163           This block may only appear inside a context handler block. It
1164           causes the surrounding handler to return the final value of the
1165           "RESULT"'s block, rather than the final value of the handler's own
1166           block. This override occurs regardless of the location to the
1167           "RESULT" block within the handler.
1168
1169   Recovery blocks
1170       "RECOVER"
1171           If present in a context return sequence, this block grabs control
1172           after any context handler returns or exits via an exception. If an
1173           exception was thrown it is passed to the "RECOVER" block via the $@
1174           variable.
1175
1176   Modifiers
1177       "FIXED"
1178           This specifies that the scalar value will only be evaluated once,
1179           the first time it is used, and that the value will then morph into
1180           that evaluated value.
1181
1182       "ACTIVE"
1183           This specifies that the scalar value's originating block will be
1184           re- evaluated every time the return value is used.
1185

DIAGNOSTICS

1187       Can't call %s in %s context";
1188           The subroutine you called uses a contextual return, but doesn't
1189           specify what to return in the particular context in which you
1190           called it. You either need to change the context in which you're
1191           calling the subroutine, or else add a context block corresponding
1192           to the offending context (or perhaps a "DEFAULT {...}" block).
1193
1194       %s can't return a %s reference";
1195           You called the subroutine in a context that expected to get back a
1196           reference of some kind but the subroutine didn't specify the
1197           corresponding "SCALARREF", "ARRAYREF", "HASHREF", "CODEREF",
1198           "GLOBREF", or generic "REF", "NONVOID", or "DEFAULT" handlers.  You
1199           need to specify the appropriate one of these handlers in the
1200           subroutine.
1201
1202       Can't call method '%s' on %s value returned by %s";
1203           You called the subroutine and then tried to call a method on the
1204           return value, but the subroutine returned a classname or object
1205           that doesn't have that method. This probably means that the
1206           subroutine didn't return the classname or object you expected. Or
1207           perhaps you need to specify an "OBJREF {...}" context block.
1208
1209       Can't install two %s handlers
1210           You attempted to specify two context blocks of the same name in the
1211           same return context, which is ambiguous. For example:
1212
1213               sub foo: lvalue {
1214                   LVALUE { $foo = $_ }
1215                   RVALUE { $foo }
1216                   LVALUE { $foo = substr($_,1,10) }
1217               }
1218
1219           or:
1220
1221               sub bar {
1222                   return
1223                       BOOL { 0 }
1224                        NUM { 1 }
1225                        STR { "two" }
1226                       BOOL { 1 };
1227               }
1228
1229           Did you cut-and-paste wrongly, or mislabel one of the blocks?
1230
1231       Expected a %s block after the %s block but found instead: %s
1232           If you specify any of "LVALUE", "RVALUE", or "NVALUE", then you can
1233           only specify "LVALUE", "RVALUE", or "NVALUE" blocks in the same
1234           return context.  If you need to specify other contexts (like
1235           "BOOL", or "STR", or "REF", etc.), put them inside an "RVALUE"
1236           block. See "Lvalue contexts" for an example.
1237
1238       Call to %s failed at %s.
1239           This is the default exception that a "FAIL" throws in a non-scalar
1240           context. Which means that the subroutine you called has signalled
1241           failure by throwing an exception, and you didn't catch that
1242           exception.  You should either put the call in an "eval {...}" block
1243           or else call the subroutine in boolean context instead.
1244
1245       Call to %s failed at %s. Failure value used at %s
1246           This is the default exception that a "FAIL" throws when a failure
1247           value is captured in a scalar variable and later used in a non-
1248           boolean context. That means that the subroutine you called must
1249           have failed, and you didn't check the return value for that
1250           failure, so when you tried to use that invalid value it killed your
1251           program. You should either put the original call in an "eval {...}"
1252           or else test the return value in a boolean context and avoid using
1253           it if it's false.
1254
1255       Usage: FAIL_WITH $flag_opt, \%selector, @args
1256           The "FAIL_WITH" subroutine expects an optional flag, followed by a
1257           reference to a configuration hash, followed by a list or selector
1258           arguments. You gave it something else. See "Configurable Failure
1259           Contexts".
1260
1261       Selector values must be sub refs
1262           You passed a configuration hash to "FAIL_WITH" that specified non-
1263           subroutines as possible "FAIL" handlers. Since non-subroutines
1264           can't possibly be handlers, maybe you forgot the "sub" keyword
1265           somewhere?
1266
1267       Invalid option: %s => %s
1268           The "FAIL_WITH" subroutine was passed a flag/selector pair, but the
1269           selector was not one of those allowed by the configuration hash.
1270
1271       FAIL handler for package %s redefined
1272           A warning that the "FAIL" handler for a particular package was
1273           reconfigured more than once. Typically that's because the module
1274           was loaded in two places with difference configurations specified.
1275           You can't reasonably expect two different sets of behaviours from
1276           the one module within the one namespace.
1277

CONFIGURATION AND ENVIRONMENT

1279       Contextual::Return requires no configuration files or environment
1280       variables.
1281

DEPENDENCIES

1283       Requires version.pm and Want.pm.
1284

INCOMPATIBILITIES

1286       None reported.
1287

BUGS AND LIMITATIONS

1289       No bugs have been reported.
1290

AUTHOR

1292       Damian Conway  "<DCONWAY@cpan.org>"
1293
1295       Copyright (c) 2005-2006, Damian Conway "<DCONWAY@cpan.org>". All rights
1296       reserved.
1297
1298       This module is free software; you can redistribute it and/or modify it
1299       under the same terms as Perl itself.
1300

DISCLAIMER OF WARRANTY

1302       BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
1303       FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT
1304       WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER
1305       PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND,
1306       EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1307       WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
1308       ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
1309       YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
1310       NECESSARY SERVICING, REPAIR, OR CORRECTION.
1311
1312       IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
1313       WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
1314       REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE
1315       TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR
1316       CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
1317       SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
1318       RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
1319       FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
1320       SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
1321       DAMAGES.
1322
1323
1324
1325perl v5.12.0                      2007-03-29             Contextual::Return(3)
Impressum