1Contextual::Return(3) User Contributed Perl DocumentationContextual::Return(3)
2
3
4
6 Contextual::Return - Create context-sensitive return values
7
9 This document describes Contextual::Return version 0.004014
10
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
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 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
634 returned a true value (namely, the string:
635 'Contextual::Return::Value'), even if the return value had not
636 specified handlers for "OBJREF" or "METHOD".
637
638 In other words, the implementation of contextual return values (as
639 objects) was getting in the way of the use of contextual return values
640 (as non-objects).
641
642 So the module now also provides a "BLESSED" handler, which allows you
643 to explicitly control how contextual return values interact with
644 "Scalar::Util::blessed()".
645
646 If $crv is a contextual return value, by default
647 "Scalar::Util::blessed($crv)" will now only return true if that return
648 value has a "OBJREF", "LAZY", "REF", "SCALAR", "VALUE", "NONVOID", or
649 "DEFAULT" handler that in turn returns a blessed object.
650
651 However if $crv also provides a "BLESSED" handler, "blessed()" will
652 return whatever that handler returns.
653
654 This means:
655
656 sub simulate_non_object {
657 return BOOL { 1 }
658 NUM { 42 }
659 }
660
661 sub simulate_real_object {
662 return OBJREF { bless {}, 'My::Class' }
663 BOOL { 1 }
664 NUM { 42 }
665 }
666
667 sub simulate_faked_object {
668 return BLESSED { 'Foo' }
669 BOOL { 1 }
670 NUM { 42 }
671 }
672
673 sub simulate_previous_behaviour {
674 return BLESSED { 'Contextual::Return::Value' }
675 BOOL { 1 }
676 NUM { 42 }
677 }
678
679
680 say blessed( simulate_non_object() ); # undef
681 say blessed( simulate_real_object() ); # My::Class
682 say blessed( simulate_faked_object() ); # Foo
683 say blessed( simulate_previous_behaviour() ); # Contextual::Return::Value
684
685 Typically, you either want no "BLESSED" handler (in which case
686 contextual return values pretend not to be blessed objects), or you
687 want "BLESSED { 'Contextual::Return::Value' }" for backwards
688 compatibility with pre-v0.4.7 behaviour.
689
690 Preventing fallbacks
691
692 Sometimes fallbacks can be too helpful. Or sometimes you want to impose
693 strict type checking on a return value.
694
695 Contextual::Returns allows that via the "STRICT" specifier. If you
696 include "STRICT" anywhere in your return statement, the module disables
697 all fallbacks and will therefore through an exception if the return
698 value is used in any way not explicitly specified in the contextual
699 return sequence.
700
701 For example, to create a subroutine that returns only a string:
702
703 sub get_name {
704 return STRICT STR { 'Bruce' }
705 }
706
707 If the return value of the subroutine is used in any other way than as
708 a string, an exception will be thrown.
709
710 You can still specify handlers for more than a single kind of context
711 when using "STRICT":
712
713 sub get_name {
714 return STRICT
715 STR { 'Bruce' }
716 BOOL { 0 }
717 }
718
719 ...but these will still be the only contexts in which the return value
720 can be used:
721
722 my $n = get_name() ? 1 : 2; # Okay because BOOL handler specified
723
724 my $n = 'Dr' . get_name(); # Okay because STR handler specified
725
726 my $n = 1 + get_name(); # Exception thrown because no NUM handler
727
728 In other words, "STRICT" allows you to impose strict type checking on
729 your contextual return value.
730
731 Deferring handlers
732 Because the various handlers form a hierarchy, it's possible to
733 implement more specific handlers by falling back on ("deferring to")
734 more general ones. For example, a "PUREBOOL" handler is almost always
735 identical in its basic behaviour to the corresponding "BOOL" handler,
736 except that it adds some side-effect. For example:
737
738 return
739 PUREBOOL { $_ = $return_val; defined $return_val && $return_val > 0 }
740 BOOL { defined $return_val && $return_val > 0 }
741 SCALAR { $return_val; }
742
743 So Contextual::Return allows you to have a handler perform some action
744 and then defer to a more general handler to supply the actual return
745 value. To fall back to a more general case in this way, you simply
746 write:
747
748 next handler;
749
750 at the end of the handler in question, after which Contextual::Return
751 will find the next-most-specific handler and execute it as well. So the
752 previous example, could be re-written:
753
754 return
755 PUREBOOL { $_ = $return_val; next handler; }
756 BOOL { defined $return_val && $return_val > 0 }
757 SCALAR { $return_val; }
758
759 Note that any specific handler can defer to a more general one in this
760 same way. For example, you could provide consistent and maintainable
761 type-checking for a subroutine that returns references by providing
762 "ARRAYREF", "HASHREF", and "SCALARREF" handlers that all defer to a
763 generic "REF" handler, like so:
764
765 my $retval = _get_ref();
766
767 return
768 SCALARREF { croak 'Type mismatch' if ref($retval) ne 'SCALAR';
769 next handler;
770 }
771 ARRAYREF { croak 'Type mismatch' if ref($retval) ne 'ARRAY';
772 next handler;
773 }
774 HASHREF { croak 'Type mismatch' if ref($retval) ne 'HASH';
775 next handler;
776 }
777 REF { $retval }
778
779 If, at a later time, the process of returning a reference became more
780 complex, only the "REF" handler would have to be updated.
781
782 Nested handlers
783 Another way of factoring out return behaviour is to nest more specific
784 handlers inside more general ones. For instance, in the final example
785 given in "Boolean vs Pure Boolean contexts":
786
787 sub get_data {
788 my $data;
789 return
790 PUREBOOL { _check_for_but_dont_get_data(); }
791 BOOL { defined( $data ||= _go_and_get_data() ); }
792 REF { $data ||= _go_and_get_data(); }
793 }
794
795 you could factor out the repeated calls to "_go_and_get_data()" like
796 so:
797
798 sub get_data {
799 return
800 PUREBOOL { _check_for_but_dont_get_data(); }
801 DEFAULT {
802 my $data = _go_and_get_data();
803
804 BOOL { defined $data; }
805 REF { $data; }
806 }
807 }
808
809 Here, the "DEFAULT" handler deals with every return context except pure
810 boolean. Within that "DEFAULT" handler, the data is first retrieved,
811 and then two "sub-handlers" deal with the ordinary boolean and
812 referential contexts.
813
814 Typically nested handlers are used in precisely this way: to optimize
815 for inexpensive special cases (such as pure boolean or integer or void
816 return contexts) and only do extra work for those other cases that
817 require it.
818
819 Failure contexts
820 Two of the most common ways to specify that a subroutine has failed are
821 to return a false value, or to throw an exception. The
822 Contextual::Return module provides a mechanism that allows the
823 subroutine writer to support both of these mechanisms at the same time,
824 by using the "FAIL" specifier.
825
826 A return statement of the form:
827
828 return FAIL;
829
830 causes the surrounding subroutine to return "undef" (i.e. false) in
831 boolean contexts, and to throw an exception in any other context. For
832 example:
833
834 use Contextual::Return;
835
836 sub get_next_val {
837 my $next_val = <>;
838 return FAIL if !defined $next_val;
839 chomp $next_val;
840 return $next_val;
841 }
842
843 If the "return FAIL" statement is executed, it will either return false
844 in a boolean context:
845
846 if (my $val = get_next_val()) { # returns undef if no next val
847 print "[$val]\n";
848 }
849
850 or else throw an exception if the return value is used in any other
851 context:
852
853 print get_next_val(); # throws exception if no next val
854
855 my $next_val = get_next_val();
856 print "[$next_val]\n"; # throws exception if no next val
857
858 The exception that is thrown is of the form:
859
860 Call to main::get_next_val() failed at demo.pl line 42
861
862 but you can change that message by providing a block to the "FAIL",
863 like so:
864
865 return FAIL { "No more data" } if !defined $next_val;
866
867 in which case, the final value of the block becomes the exception
868 message:
869
870 No more data at demo.pl line 42
871
872 A failure value can be interrogated for its error message, by calling
873 its "error()" method, like so:
874
875 my $val = get_next_val();
876 if ($val) {
877 print "[$val]\n";
878 }
879 else {
880 print $val->error, "\n";
881 }
882
883 Configurable failure contexts
884 The default "FAIL" behaviour--false in boolean context, fatal in all
885 others--works well in most situations, but violates the Platinum Rule
886 ("Do unto others as they would have done unto them").
887
888 So it may be user-friendlier if the user of a module is allowed decide
889 how the module's subroutines should behave on failure. For example, one
890 user might prefer that failing subs always return undef; another might
891 prefer that they always throw an exception; a third might prefer that
892 they always log the problem and return a special Failure object; whilst
893 a fourth user might want to get back 0 in scalar contexts, an empty
894 list in list contexts, and an exception everywhere else.
895
896 You could create a module that allows the user to specify all these
897 alternatives, like so:
898
899 package MyModule;
900 use Contextual::Return;
901 use Log::StdLog;
902
903 sub import {
904 my ($package, @args) = @_;
905
906 Contextual::Return::FAIL_WITH {
907 ':false' => sub { return undef },
908 ':fatal' => sub { croak @_ },
909 ':filed' => sub {
910 print STDLOG 'Sub ', (caller 1)[3], ' failed';
911 return Failure->new();
912 },
913 ':fussy' => sub {
914 SCALAR { undef }
915 LIST { () }
916 DEFAULT { croak @_ }
917 },
918 }, @args;
919 }
920
921 This configures Contextual::Return so that, instead of the usual false-
922 or-fatal semantics, every "return FAIL" within MyModule's namespace is
923 implemented by one of the four subroutines specified in the hash that
924 was passed to "FAIL_WITH".
925
926 Which of those four subs implements the "FAIL" is determined by the
927 arguments passed after the hash (i.e. by the contents of @args).
928 "FAIL_WITH" walks through that list of arguments and compares them
929 against the keys of the hash. If a key matches an argument, the
930 corresponding value is used as the implementation of "FAIL". Note that,
931 if subsequent arguments also match a key, their subroutine overrides
932 the previously installed implementation, so only the final override has
933 any effect. Contextual::Return generates warnings when multiple
934 overrides are specified.
935
936 All of which mean that, if a user loaded the MyModule module like this:
937
938 use MyModule qw( :fatal other args here );
939
940 then every "FAIL" within MyModule would be reconfigured to throw an
941 exception in all circumstances, since the presence of the ':fatal' in
942 the argument list will cause "FAIL_WITH" to select the hash entry whose
943 key is ':fatal'.
944
945 On the other hand, if they loaded the module:
946
947 use MyModule qw( :fussy other args here );
948
949 then each "FAIL" within MyModule would return undef or empty list or
950 throw an exception, depending on context, since that's what the
951 subroutine whose key is ':fussy' does.
952
953 Many people prefer module interfaces with a "flag => value" format, and
954 "FAIL_WITH" supports this too. For example, if you wanted your module
955 to take a "-fail" flag, whose associated value could be any of
956 "undefined", "exception", "logged", or "context", then you could
957 implement that simply by specifying the flag as the first argument
958 (i.e. before the hash) like so:
959
960 sub import {
961 my $package = shift;
962
963 Contextual::Return::FAIL_WITH -fail => {
964 'undefined' => sub { return undef },
965 'exception' => sub { croak @_ },
966 'logged' => sub {
967 print STDLOG 'Sub ', (caller 1)[3], ' failed';
968 return Failure->new();
969 },
970 'context' => sub {
971 SCALAR { undef }
972 LIST { () }
973 DEFAULT { croak @_ }
974 },
975 }, @_;
976
977 and then load the module:
978
979 use MyModule qw( other args here ), -fail=>'undefined';
980
981 or:
982
983 use MyModule qw( other args here ), -fail=>'exception';
984
985 In this case, "FAIL_WITH" scans the argument list for a pair of values:
986 its flag string, followed by some other selector value. Then it looks
987 up the selector value in the hash, and installs the corresponding
988 subroutine as its local "FAIL" handler.
989
990 If this "flagged" interface is used, the user of the module can also
991 specify their own handler directly, by passing a subroutine reference
992 as the selector value instead of a string:
993
994 use MyModule qw( other args here ), -fail=>sub{ die 'horribly'};
995
996 If this last example were used, any call to "FAIL" within MyModule
997 would invoke the specified anonymous subroutine (and hence throw a
998 'horribly' exception).
999
1000 Note that, any overriding of a "FAIL" handler is specific to the
1001 namespace and file from which the subroutine that calls "FAIL_WITH" is
1002 itself called. Since "FAIL_WITH" is designed to be called from within a
1003 module's "import()" subroutine, that generally means that the "FAIL"s
1004 within a given module X are only overridden for the current namespace
1005 within the particular file from module X is loaded. This means that two
1006 separate pieces of code (in separate files or separate namespaces) can
1007 each independently override a module's "FAIL" behaviour, without
1008 interfering with each other.
1009
1010 Lvalue contexts
1011 Recent versions of Perl offer (limited) support for lvalue subroutines:
1012 subroutines that return a modifiable variable, rather than a simple
1013 constant value.
1014
1015 Contextual::Return can make it easier to create such subroutines,
1016 within the limitations imposed by Perl itself. The limitations that
1017 Perl places on lvalue subs are:
1018
1019 1. The subroutine must be declared with an ":lvalue" attribute:
1020
1021 sub foo :lvalue {...}
1022
1023 2. The subroutine must not return via an explicit "return". Instead,
1024 the last statement must evaluate to a variable, or must be a call
1025 to another lvalue subroutine call.
1026
1027 my ($foo, $baz);
1028
1029 sub foo :lvalue {
1030 $foo; # last statement evals to a var
1031 }
1032
1033 sub bar :lvalue {
1034 foo(); # last statement is lvalue sub call
1035 }
1036
1037 sub baz :lvalue {
1038 my ($arg) = @_;
1039
1040 $arg > 0 # last statement evals...
1041 ? $baz # ...to a var
1042 : bar(); # ...or to an lvalue sub call
1043 }
1044
1045 Thereafter, any call to the lvalue subroutine produces a result that
1046 can be assigned to:
1047
1048 baz(0) = 42; # same as: $baz = 42
1049
1050 baz(1) = 84; # same as: bar() = 84
1051 # which is the same as: foo() = 84
1052 # which is the same as: $foo = 84
1053
1054 Ultimately, every lvalue subroutine must return a scalar variable,
1055 which is then used as the lvalue of the assignment (or whatever other
1056 lvalue operation is applied to the subroutine call). Unfortunately,
1057 because the subroutine has to return this variable before the
1058 assignment can take place, there is no way that a normal lvalue
1059 subroutine can get access to the value that will eventually be assigned
1060 to its return value.
1061
1062 This is occasionally annoying, so the Contextual::Return module offers
1063 a solution: in addition to all the context blocks described above, it
1064 provides three special contextual return blocks specifically for use in
1065 lvalue subroutines: "LVALUE", "RVALUE", and "NVALUE".
1066
1067 Using these blocks you can specify what happens when an lvalue
1068 subroutine is used in lvalue and non-lvalue (rvalue) context. For
1069 example:
1070
1071 my $verbosity_level = 1;
1072
1073 # Verbosity values must be between 0 and 5...
1074 sub verbosity :lvalue {
1075 LVALUE { $verbosity_level = max(0, min($_, 5)) }
1076 RVALUE { $verbosity_level }
1077 }
1078
1079 The "LVALUE" block is executed whenever "verbosity" is called as an
1080 lvalue:
1081
1082 verbosity() = 7;
1083
1084 The block has access to the value being assigned, which is passed to it
1085 as $_. So, in the above example, the assigned value of 7 would be
1086 aliased to $_ within the "LVALUE" block, would be reduced to 5 by the
1087 "min-of-max" expression, and then assigned to $verbosity_level.
1088
1089 (If you need to access the caller's $_, it's also still available: as
1090 $CALLER::_.)
1091
1092 When the subroutine isn't used as an lvalue:
1093
1094 print verbosity();
1095
1096 the "RVALUE" block is executed instead and its final value returned.
1097 Within an "RVALUE" block you can use any of the other features of
1098 Contextual::Return. For example:
1099
1100 sub verbosity :lvalue {
1101 LVALUE { $verbosity_level = int max(0, min($_, 5)) }
1102 RVALUE {
1103 NUM { $verbosity_level }
1104 STR { $description[$verbosity_level] }
1105 BOOL { $verbosity_level > 2 }
1106 }
1107 }
1108
1109 but the context sequence must be nested inside an "RVALUE" block.
1110
1111 You can also specify what an lvalue subroutine should do when it is
1112 used neither as an lvalue nor as an rvalue (i.e. in void context), by
1113 using an "NVALUE" block:
1114
1115 sub verbosity :lvalue {
1116 my ($level) = @_;
1117
1118 NVALUE { $verbosity_level = int max(0, min($level, 5)) }
1119 LVALUE { $verbosity_level = int max(0, min($_, 5)) }
1120 RVALUE {
1121 NUM { $verbosity_level }
1122 STR { $description[$verbosity_level] }
1123 BOOL { $verbosity_level > 2 }
1124 }
1125 }
1126
1127 In this example, a call to "verbosity()" in void context sets the
1128 verbosity level to whatever argument is passed to the subroutine:
1129
1130 verbosity(1);
1131
1132 Note that you cannot get the same effect by nesting a "VOID" block
1133 within an "RVALUE" block:
1134
1135 LVALUE { $verbosity_level = int max(0, min($_, 5)) }
1136 RVALUE {
1137 NUM { $verbosity_level }
1138 STR { $description[$verbosity_level] }
1139 BOOL { $verbosity_level > 2 }
1140 VOID { $verbosity_level = $level } # Wrong!
1141 }
1142
1143 That's because, in a void context the return value is never evaluated,
1144 so it is never treated as an rvalue, which means the "RVALUE" block
1145 never executes.
1146
1147 Result blocks
1148 Occasionally, it's convenient to calculate a return value before the
1149 end of a contextual return block. For example, you may need to clean up
1150 external resources involved in the calculation after it's complete.
1151 Typically, this requirement produces a slightly awkward code sequence
1152 like this:
1153
1154 return
1155 VALUE {
1156 $db->start_work();
1157 my $result = $db->retrieve_query($query);
1158 $db->commit();
1159 $result;
1160 }
1161
1162 Such code sequences become considerably more awkward when you want the
1163 return value to be context sensitive, in which case you have to write
1164 either:
1165
1166 return
1167 LIST {
1168 $db->start_work();
1169 my @result = $db->retrieve_query($query);
1170 $db->commit();
1171 @result;
1172 }
1173 SCALAR {
1174 $db->start_work();
1175 my $result = $db->retrieve_query($query);
1176 $db->commit();
1177 $result;
1178 }
1179
1180 or, worse:
1181
1182 return
1183 VALUE {
1184 $db->start_work();
1185 my $result = LIST ? [$db->retrieve_query($query)]
1186 : $db->retrieve_query($query);
1187 $db->commit();
1188 LIST ? @{$result} : $result;
1189 }
1190
1191 To avoid these infelicities, Contextual::Return provides a second way
1192 of setting the result of a context block; a way that doesn't require
1193 that the result be the last statement in the block:
1194
1195 return
1196 LIST {
1197 $db->start_work();
1198 RESULT { $db->retrieve_query($query) };
1199 $db->commit();
1200 }
1201 SCALAR {
1202 $db->start_work();
1203 RESULT { $db->retrieve_query($query) };
1204 $db->commit();
1205 }
1206
1207 The presence of a "RESULT" block inside a contextual return block
1208 causes that block to return the value of the final statement of the
1209 "RESULT" block as the handler's return value, rather than returning the
1210 value of the handler's own final statement. In other words, the
1211 presence of a "RESULT" block overrides the normal return value of a
1212 context handler.
1213
1214 Better still, the "RESULT" block always evaluates its final statement
1215 in the same context as the surrounding "return", so you can just write:
1216
1217 return
1218 VALUE {
1219 $db->start_work();
1220 RESULT { $db->retrieve_query($query) };
1221 $db->commit();
1222 }
1223
1224 and the "retrieve_query()" method will be called in the appropriate
1225 context in all cases.
1226
1227 A "RESULT" block can appear anywhere inside any contextual return
1228 block, but may not be used outside a context block. That is, this is an
1229 error:
1230
1231 if ($db->closed) {
1232 RESULT { undef }; # Error: not in a context block
1233 }
1234 return
1235 VALUE {
1236 $db->start_work();
1237 RESULT { $db->retrieve_query($query) };
1238 $db->commit();
1239 }
1240
1241 Post-handler clean-up
1242 If a subroutine uses an external resource, it's often necessary to
1243 close or clean-up that resource after the subroutine ends...regardless
1244 of whether the subroutine exits normally or via an exception.
1245
1246 Typically, this is done by encapsulating the resource in a lexically
1247 scoped object whose destructor does the clean-up. However, if the
1248 clean-up doesn't involve deallocation of an object (as in the
1249 "$db->commit()" example in the previous section), it can be annoying to
1250 have to create a class and allocate a container object, merely to
1251 mediate the clean-up.
1252
1253 To make it easier to manage such resources, Contextual::Return supplies
1254 a special labelled block: the "RECOVER" block. If a "RECOVER" block is
1255 specified as part of a contextual return sequence, that block is
1256 executed after any context handler, even if the context handler exits
1257 via an exception.
1258
1259 So, for example, you could implement a simple commit-or-revert policy
1260 like so:
1261
1262 return
1263 LIST { $db->retrieve_all($query) }
1264 SCALAR { $db->retrieve_next($query) }
1265 RECOVER {
1266 if ($@) {
1267 $db->revert();
1268 }
1269 else {
1270 $db->commit();
1271 }
1272 }
1273
1274 The presence of a "RECOVER" block also intercepts all exceptions thrown
1275 in any other context block in the same contextual return sequence. Any
1276 such exception is passed into the "RECOVER" block in the usual manner:
1277 via the $@ variable. The exception may be rethrown out of the "RECOVER"
1278 block by calling "die":
1279
1280 return
1281 LIST { $db->retrieve_all($query) }
1282 DEFAULT { croak "Invalid call (not in list context)" }
1283 RECOVER {
1284 die $@ if $@; # Propagate any exception
1285 $db->commit(); # Otherwise commit the changes
1286 }
1287
1288 A "RECOVER" block can also access or replace the returned value, by
1289 invoking a "RESULT" block. For example:
1290
1291 return
1292 LIST { attempt_to_generate_list_for(@_) }
1293 SCALAR { attempt_to_generate_count_for(@_) }
1294 RECOVER {
1295 if ($@) { # On any exception...
1296 warn "Replacing return value. Previously: ", RESULT;
1297 RESULT { undef } # ...return undef
1298 }
1299 }
1300
1301 Post-return clean-up
1302 Occasionally it's necessary to defer the clean-up of resources until
1303 after the return value has been used. Once again, this is usually done
1304 by returning an object with a suitable destructor.
1305
1306 Using Contextual::Return you can get the same effect, by providing a
1307 "CLEANUP" block in the contextual return sequence:
1308
1309 return
1310 LIST { $db->retrieve_all($query) }
1311 SCALAR { $db->retrieve_next($query) }
1312 CLEANUP { $db->commit() }
1313
1314 In this example, the "commit" method call is only performed after the
1315 return value has been used by the caller. Note that this is quite
1316 different from using a "RECOVER" block, which is called as the
1317 subroutine returns its value; a "CLEANUP" is called when the returned
1318 value is garbage collected.
1319
1320 A "CLEANUP" block is useful for controlling resources allocated to
1321 support an "ACTIVE" return value. For example:
1322
1323 my %file;
1324
1325 # Return an active value that is always the next line from a file...
1326 sub readline_from {
1327 my ($file_name) = @_;
1328
1329 # Open the file, if not already open...
1330 if (!$file{$file_name}) {
1331 open $file{$file_name}{handle}, '<', $file_name;
1332 }
1333
1334 # Track how many active return values are using this file...
1335 $file{$file_name}{count}++;
1336
1337 return ACTIVE
1338 # Evaluating the return value returns the next line...
1339 VALUE { readline $file{$file_name}{handle} }
1340
1341 # Once the active value is finished with, clean up the filehandle...
1342 CLEANUP {
1343 delete $file{$file_name}
1344 if --$file{$file_name}{count} == 0;
1345 }
1346 }
1347
1348 Debugging contextual return values
1349 Contextual return values are implemented as opaque objects (using the
1350 "inside-out" technique). This means that passing such values to
1351 Data::Dumper produces an uninformative output like:
1352
1353 $VAR1 = bless( do{\(my $o = undef)}, 'Contextual::Return::Value' );
1354
1355 So the module provides two methods that allow contextual return values
1356 to be correctly reported: either directly, or when dumped by
1357 Data::Dumper.
1358
1359 To dump a contextual return value directly, call the module's "DUMP()"
1360 method explicitly and print the result:
1361
1362 print $crv->Contextual::Return::DUMP();
1363
1364 This produces an output something like:
1365
1366 [
1367 { FROM => 'main::foo' },
1368 { NO_HANDLER => [ 'VOID', 'CODEREF', 'HASHREF', 'GLOBREF' ] },
1369 { FALLBACKS => [ 'VALUE' ] },
1370 { LIST => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] },
1371 { STR => '<<<Throws exception: Died at demo.pl line 7.>>>' },
1372 { NUM => 42 },
1373 { BOOL => -1 },
1374 { SCALARREF => '<<<self-reference>>>' },
1375 { ARRAYREF => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] },
1376 ];
1377
1378 The "FROM" hash entry names the subroutine that produced the return
1379 value. The "NO_HANDLER" hash entry lists those contexts for which no
1380 handler was defined (and which would therefore normally produce "can't
1381 call" exceptions such as: "Can't call main::foo in VOID context"). The
1382 "FALLBACKS" hash entry lists any "generic" contexts such as "VALUE",
1383 "NONVOID", "REF", "DEFAULT", etc. that the contextual return value can
1384 also handle. After these, all the remaining hash entries are actual
1385 contexts in which the return value could successfully be evaluated, and
1386 the value it would produce in each of those contexts.
1387
1388 The Data::Dumper module also has a mechanism by which you can tell it
1389 how to produce a similar listing automatically whenever a contextual
1390 return value is passed to its "Dumper" method. Data::Dumper allows you
1391 to register a "freezer" method, that is called prior to dumping, and
1392 which can be used to adapt an opaque object to make it dumpable.
1393 Contextual::Return provides just such a method
1394 ("Contextual::Return::FREEZE()") for you to register, like so:
1395
1396 use Data::Dumper 'Dumper';
1397
1398 local $Data::Dumper::Freezer = 'Contextual::Return::FREEZE';
1399
1400 print Dumper $foo;
1401
1402 The output is then precisely the same as "Contextual::Return::DUMP()"
1403 would produce.
1404
1405 Note that, with both of the above dumping mechanisms, it is essential
1406 to use the full name of the method. That is:
1407
1408 print $crv->Contextual::Return::DUMP();
1409
1410 rather than:
1411
1412 print $crv->DUMP();
1413
1414 This is because the shorter version is interpreted as calling the
1415 "DUMP()" method on the object returned by the return value's "OBJREF"
1416 context block (see "Scalar reference contexts")
1417
1418 For the same reason, you must write:
1419
1420 local $Data::Dumper::Freezer = 'Contextual::Return::FREEZE';
1421
1422 not:
1423
1424 local $Data::Dumper::Freezer = 'FREEZE';
1425
1426 Namespace controls
1427 By default the module exports a large number of return context markers:
1428
1429 DEFAULT REF LAZY
1430 VOID SCALARREF FIXED
1431 NONVOID ARRAYREF ACTIVE
1432 LIST CODEREF RESULT
1433 SCALAR HASHREF RECOVER
1434 VALUE GLOBREF CLEANUP
1435 STR OBJREF RVALUE
1436 NUM METHOD LVALUE
1437 BOOL NVALUE
1438 PUREBOOL
1439
1440 These are exported as subroutines, and so can conflict with existing
1441 subroutines in your namespace, or with subroutines imported from other
1442 modules.
1443
1444 Contextual::Return allows you to control which contextual return blocks
1445 are exported into any namespace that uses the module. It also allows
1446 you to rename blocks to avoid namespace conflicts with existing
1447 subroutines.
1448
1449 Both these features are controlled by passing arguments to the "use"
1450 statement that loads the module as follows:
1451
1452 • Any string passed as an argument to "use Contextual::Return",
1453 exports only the block name it specifies;
1454
1455 • Any regex passed as an argument to "use Contextual::Return" exports
1456 every block name it matches;
1457
1458 • Any array ref (recursively) exports each of its elements
1459
1460 • Any string that appears immediately after one of the above three
1461 specifiers, and which is not itself a block name, renames the
1462 handlers exported by that preceding specifier by filtering each
1463 handler name through "sprintf()"
1464
1465 That is, you can specify handlers to be exported by exact name (as a
1466 string), by general pattern (as a regex), or collectively (in an
1467 array). And after any of these export specifications, you can append a
1468 template in which any '%s' will be replaced by the original name of the
1469 handler. For example:
1470
1471 # Selectively export specific sets of handlers...
1472 use Contextual::Return qr/[NLR]VALUE/;
1473 use Contextual::Return qr/.*REF/;
1474
1475 # Selective export specific sets and add a suffix to each...
1476 use Contextual::Return qr/[NLR]VALUE/ => '%s_CONTEXT';
1477
1478 # Selective export specific sets and add a prefix to each...
1479 use Contextual::Return qr/.*REF/ => 'CR_%s';
1480
1481 # Export a list of handlers...
1482 use Contextual::Return 'NUM', 'STR', 'BOOL' ;
1483 use Contextual::Return qw< NUM STR BOOL >;
1484 use Contextual::Return ['NUM', 'STR', 'BOOL'];
1485
1486 # Export a list of handlers, renaming them individually...
1487 use Contextual::Return NUM => 'NUMERIC', STR => 'TEXT', BOOL => 'CR_%s';
1488
1489 # Export a list of handlers, renaming them collectively...
1490 use Contextual::Return ['NUM', 'STR', 'BOOL'] => '%s_CONTEXT';
1491
1492 # Mixed exports and renames...
1493 use Contextual::Return (
1494 STR => 'TEXT',
1495 ['NUM', 'BOOL'] => 'CR_%s',
1496 ['LIST', 'SCALAR', 'VOID', qr/^[NLR]VALUE/] => '%s_CONTEXT',
1497 );
1498
1500 Context tests
1501 "LIST()"
1502 Returns true if the current subroutine was called in list context.
1503 A cleaner way of writing: "wantarray()"
1504
1505 "SCALAR()"
1506 Returns true if the current subroutine was called in scalar
1507 context. A cleaner way of writing: "defined wantarray() && !
1508 wantarray()"
1509
1510 "VOID()"
1511 Returns true if the current subroutine was called in void context.
1512 A cleaner way of writing: "!defined wantarray()"
1513
1514 "NONVOID()"
1515 Returns true if the current subroutine was called in list or scalar
1516 context. A cleaner way of writing: "defined wantarray()"
1517
1518 Standard contexts
1519 "LIST {...}"
1520 The block specifies what the context sequence should evaluate to
1521 when called in list context.
1522
1523 "SCALAR {...}"
1524 The block specifies what the context sequence should evaluate to in
1525 scalar contexts, unless some more-specific specifier scalar context
1526 specifier (see below) also occurs in the same context sequence.
1527
1528 "VOID {...}"
1529 The block specifies what the context sequence should do when called
1530 in void context.
1531
1532 Scalar value contexts
1533 "BOOL {...}"
1534 The block specifies what the context sequence should evaluate to
1535 when treated as a boolean value.
1536
1537 "NUM {...}"
1538 The block specifies what the context sequence should evaluate to
1539 when treated as a numeric value.
1540
1541 "STR {...}"
1542 The block specifies what the context sequence should evaluate to
1543 when treated as a string value.
1544
1545 "LAZY {...}"
1546 Another name for "SCALAR {...}". Usefully self-documenting when the
1547 primary purpose of the contextual return is to defer evaluation of
1548 the return value until it's actually required.
1549
1550 Scalar reference contexts
1551 "SCALARREF {...}"
1552 The block specifies what the context sequence should evaluate to
1553 when treated as a reference to a scalar.
1554
1555 "ARRAYREF {...}"
1556 The block specifies what the context sequence should evaluate to
1557 when treated as a reference to an array.
1558
1559 "HASHREF {...}"
1560 The block specifies what the context sequence should evaluate to
1561 when treated as a reference to a hash.
1562
1563 Note that a common error here is to write:
1564
1565 HASHREF { a=>1, b=>2, c=>3 }
1566
1567 The curly braces there are a block, not a hash constructor, so the
1568 block doesn't return a hash reference and the interpreter throws an
1569 exception. What's needed is:
1570
1571 HASHREF { {a=>1, b=>2, c=>3} }
1572
1573 in which the inner braces are a hash constructor.
1574
1575 "CODEREF {...}"
1576 The block specifies what the context sequence should evaluate to
1577 when treated as a reference to a subroutine.
1578
1579 "GLOBREF {...}"
1580 The block specifies what the context sequence should evaluate to
1581 when treated as a reference to a typeglob.
1582
1583 "OBJREF {...}"
1584 The block specifies what the context sequence should evaluate to
1585 when treated as a reference to an object.
1586
1587 "METHOD {...}"
1588 The block can be used to specify particular handlers for specific
1589 method calls when the return value is treated as an object
1590 reference. It should return a list of methodname/methodbody pairs.
1591 Each method name can be specified as a string, a regex, or an array
1592 of strings or regexes. The method bodies must be specified as
1593 subroutine references (usually anonymous subs). The first method
1594 name that matches the actual method call selects the corresponding
1595 handler, which is then called.
1596
1597 Generic contexts
1598 "VALUE {...}"
1599 The block specifies what the context sequence should evaluate to
1600 when treated as a non-referential value (as a boolean, numeric,
1601 string, scalar, or list). Only used if there is no more-specific
1602 value context specifier in the context sequence.
1603
1604 "REF {...}"
1605 The block specifies what the context sequence should evaluate to
1606 when treated as a reference of any kind. Only used if there is no
1607 more-specific referential context specifier in the context
1608 sequence.
1609
1610 "NONVOID {...}"
1611 The block specifies what the context sequence should evaluate to
1612 when used in a non-void context of any kind. Only used if there is
1613 no more-specific context specifier in the context sequence.
1614
1615 "DEFAULT {...}"
1616 The block specifies what the context sequence should evaluate to
1617 when used in a void or non-void context of any kind. Only used if
1618 there is no more-specific context specifier in the context
1619 sequence.
1620
1621 Failure context
1622 "FAIL"
1623 This block is executed unconditionally and is used to indicate
1624 failure. In a Boolean context it return false. In all other
1625 contexts it throws an exception consisting of the final evaluated
1626 value of the block.
1627
1628 That is, using "FAIL":
1629
1630 return FAIL { "Could not defenestrate the widget" }
1631
1632 is exactly equivalent to writing:
1633
1634 return BOOL { 0 } DEFAULT { croak "Could not defenestrate the
1635 widget" }
1636
1637 except that the reporting of errors is a little smarter under
1638 "FAIL".
1639
1640 If "FAIL" is called without specifying a block:
1641
1642 return FAIL;
1643
1644 it is equivalent to:
1645
1646 return FAIL { croak "Call to <subname> failed" }
1647
1648 (where "<subname>" is replaced with the name of the surrounding
1649 subroutine).
1650
1651 Note that, because "FAIL" implicitly covers every possible return
1652 context, it cannot be chained with other context specifiers.
1653
1654 "Contextual::Return::FAIL_WITH"
1655 This subroutine is not exported, but may be called directly to
1656 reconfigure "FAIL" behaviour in the caller's namespace.
1657
1658 The subroutine is called with an optional string (the flag),
1659 followed by a mandatory hash reference (the configurations hash),
1660 followed by a list of zero-or-more strings (the selector list). The
1661 values of the configurations hash must all be subroutine
1662 references.
1663
1664 If the optional flag is specified, "FAIL_WITH" searches the
1665 selector list looking for that string, then uses the following item
1666 in the selector list as its selector value. If that selector value
1667 is a string, "FAIL_WITH" looks up that key in the hash, and
1668 installs the corresponding subroutine as the namespace's "FAIL"
1669 handler (an exception is thrown if the selector string is not a
1670 valid key of the configurations hash). If the selector value is a
1671 subroutine reference, "FAIL_WITH" installs that subroutine as the
1672 "FAIL" handler.
1673
1674 If the optional flag is not specified, "FAIL_WITH" searches the
1675 entire selector list looking for the last element that matches any
1676 key in the configurations hash. It then looks up that key in the
1677 hash, and installs the corresponding subroutine as the namespace's
1678 "FAIL" handler.
1679
1680 See "Configurable failure contexts" for examples of using this
1681 feature.
1682
1683 Lvalue contexts
1684 "LVALUE"
1685 This block is executed when the result of an ":lvalue" subroutine
1686 is assigned to. The assigned value is passed to the block as $_. To
1687 access the caller's $_ value, use $CALLER::_.
1688
1689 "RVALUE"
1690 This block is executed when the result of an ":lvalue" subroutine
1691 is used as an rvalue. The final value that is evaluated in the
1692 block becomes the rvalue.
1693
1694 "NVALUE"
1695 This block is executed when an ":lvalue" subroutine is evaluated in
1696 void context.
1697
1698 Explicit result blocks
1699 "RESULT"
1700 This block may only appear inside a context handler block. It
1701 causes the surrounding handler to return the final value of the
1702 "RESULT"'s block, rather than the final value of the handler's own
1703 block. This override occurs regardless of the location to the
1704 "RESULT" block within the handler.
1705
1706 If called without a trailing "{...}", it simply returns the current
1707 result value in scalar contexts, or the list of result values in
1708 list context.
1709
1710 Recovery blocks
1711 "RECOVER"
1712 If present in a context return sequence, this block grabs control
1713 after any context handler returns or exits via an exception. If an
1714 exception was thrown it is passed to the "RECOVER" block via the $@
1715 variable.
1716
1717 Clean-up blocks
1718 "CLEANUP"
1719 If present in a context return sequence, this block grabs control
1720 when a return value is garbage collected.
1721
1722 Modifiers
1723 "FIXED"
1724 This specifies that the scalar value will only be evaluated once,
1725 the first time it is used, and that the value will then morph into
1726 that evaluated value.
1727
1728 "ACTIVE"
1729 This specifies that the scalar value's originating block will be
1730 re- evaluated every time the return value is used.
1731
1732 Debugging support
1733 "$crv->Contextual::Return::DUMP()"
1734 Return a dumpable representation of the return value in all viable
1735 contexts.
1736
1737 "local $Data::Dumper::Freezer = 'Contextual::Return::FREEZE';"
1738 "local $Data::Dumper::Freezer = \&Contextual::Return::FREEZE;"
1739 Configure Data::Dumper to correctly dump a representation of the
1740 contextual return value.
1741
1743 "Can't use %s as export specifier"
1744 In your "use Contextual::Return" statement you specified something
1745 (such as a hash or coderef) that can't be used to select what the
1746 module exports. Make sure the list of selectors includes only
1747 strings, regexes, or references to arrays of strings or regexes.
1748
1749 "use Contextual::Return qr{%s} didn't export anything"
1750 In your "use Contextual::Return" statement you specified a regex to
1751 select which handlers to support, but the regex didn't select any
1752 handlers. Check that the regex you're using actually does match at
1753 least one of the names of the modules many handlers.
1754
1755 "Can't export %s: no such handler"
1756 In your "use Contextual::Return" statement you specified a string
1757 as the name of a context handler to be exported, but the module
1758 doesn't export a handler of that name. Check the spelling for the
1759 requested export.
1760
1761 "Can't call %s in a %s context"
1762 "Can't use return value of %s in a %s context"
1763 The subroutine you called uses a contextual return, but doesn't
1764 specify what to return in the particular context in which you
1765 called it. You either need to change the context in which you're
1766 calling the subroutine, or else add a context block corresponding
1767 to the offending context (or perhaps a "DEFAULT {...}" block).
1768
1769 "Can't call bare %s {...} in %s context"
1770 You specified a handler (such as "VOID {...}" or "LIST {...}")
1771 outside any subroutine, and in a context that it can't handle. Did
1772 you mean to place the handler outside of a subroutine? If so, then
1773 you need to put it in a context it can actually handle. Otherwise,
1774 perhaps you need to replace the trailing block with parens (that
1775 is: "VOID()" or "LIST()").
1776
1777 "Call to %s at %s didn't return a %s reference""
1778 You called the subroutine in a context that expected to get back a
1779 reference of some kind but the subroutine didn't specify the
1780 corresponding "SCALARREF", "ARRAYREF", "HASHREF", "CODEREF",
1781 "GLOBREF", or generic "REF", "NONVOID", or "DEFAULT" handlers. You
1782 need to specify the appropriate one of these handlers in the
1783 subroutine.
1784
1785 "Can't call method '%s' on %s value returned by %s""
1786 You called the subroutine and then tried to call a method on the
1787 return value, but the subroutine returned a classname or object
1788 that doesn't have that method. This probably means that the
1789 subroutine didn't return the classname or object you expected. Or
1790 perhaps you need to specify an "OBJREF {...}" context block.
1791
1792 "Can't install two %s handlers"
1793 You attempted to specify two context blocks of the same name in the
1794 same return context, which is ambiguous. For example:
1795
1796 sub foo: lvalue {
1797 LVALUE { $foo = $_ }
1798 RVALUE { $foo }
1799 LVALUE { $foo = substr($_,1,10) }
1800 }
1801
1802 or:
1803
1804 sub bar {
1805 return
1806 BOOL { 0 }
1807 NUM { 1 }
1808 STR { "two" }
1809 BOOL { 1 };
1810 }
1811
1812 Did you cut-and-paste wrongly, or mislabel one of the blocks?
1813
1814 "Expected a %s block after the %s block but found instead: %s"
1815 If you specify any of "LVALUE", "RVALUE", or "NVALUE", then you can
1816 only specify "LVALUE", "RVALUE", or "NVALUE" blocks in the same
1817 return context. If you need to specify other contexts (like
1818 "BOOL", or "STR", or "REF", etc.), put them inside an "RVALUE"
1819 block. See "Lvalue contexts" for an example.
1820
1821 "Call to %s failed at %s"
1822 This is the default exception that a "FAIL" throws in a non-scalar
1823 context. Which means that the subroutine you called has signalled
1824 failure by throwing an exception, and you didn't catch that
1825 exception. You should either put the call in an "eval {...}" block
1826 or else call the subroutine in boolean context instead.
1827
1828 "Call to %s failed at %s. Attempted to use failure value at %s"
1829 This is the default exception that a "FAIL" throws when a failure
1830 value is captured in a scalar variable and later used in a non-
1831 boolean context. That means that the subroutine you called must
1832 have failed, and you didn't check the return value for that
1833 failure, so when you tried to use that invalid value it killed your
1834 program. You should either put the original call in an "eval {...}"
1835 or else test the return value in a boolean context and avoid using
1836 it if it's false.
1837
1838 "Usage: FAIL_WITH $flag_opt, \%selector, @args"
1839 The "FAIL_WITH" subroutine expects an optional flag, followed by a
1840 reference to a configuration hash, followed by a list or selector
1841 arguments. You gave it something else. See "Configurable Failure
1842 Contexts".
1843
1844 "Selector values must be sub refs"
1845 You passed a configuration hash to "FAIL_WITH" that specified non-
1846 subroutines as possible "FAIL" handlers. Since non-subroutines
1847 can't possibly be handlers, maybe you forgot the "sub" keyword
1848 somewhere?
1849
1850 "Invalid option: %s =" %s>
1851 The "FAIL_WITH" subroutine was passed a flag/selector pair, but the
1852 selector was not one of those allowed by the configuration hash.
1853
1854 "FAIL handler for package %s redefined"
1855 A warning that the "FAIL" handler for a particular package was
1856 reconfigured more than once. Typically that's because the module
1857 was loaded in two places with difference configurations specified.
1858 You can't reasonably expect two different sets of behaviours from
1859 the one module within the one namespace.
1860
1862 Contextual::Return requires no configuration files or environment
1863 variables.
1864
1866 Requires version.pm and Want.pm.
1867
1869 "LVALUE", "RVALUE", and "NVALUE" do not work correctly under the Perl
1870 debugger. This seems to be because the debugger injects code to capture
1871 the return values from subroutines, which interferes destructively with
1872 the optional final arguments that allow "LVALUE", "RVALUE", and
1873 "NVALUE" to cascade within a single return.
1874
1876 No bugs have been reported.
1877
1879 Damian Conway "<DCONWAY@cpan.org>"
1880
1882 Copyright (c) 2005-2011, Damian Conway "<DCONWAY@cpan.org>". All rights
1883 reserved.
1884
1885 This module is free software; you can redistribute it and/or modify it
1886 under the same terms as Perl itself.
1887
1889 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
1890 FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT
1891 WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER
1892 PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND,
1893 EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1894 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
1895 ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
1896 YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
1897 NECESSARY SERVICING, REPAIR, OR CORRECTION.
1898
1899 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
1900 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
1901 REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE
1902 TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR
1903 CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
1904 SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
1905 RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
1906 FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
1907 SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
1908 DAMAGES.
1909
1910
1911
1912perl v5.36.0 2022-07-22 Contextual::Return(3)