1Contextual::Return(3) User Contributed Perl DocumentationContextual::Return(3)
2
3
4
6 Contextual::Return - Create context-senstive return values
7
9 This document describes Contextual::Return version 0.2.1
10
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
45 Usually, when you need to create a subroutine that returns different
46 values in different contexts (list, scalar, or void), you write some‐
47 thing 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
95 Those three subroutines can also be used in another way: as labels on a
96 series of contextual return blocks (collectively known as a contextual
97 return sequence). When a context sequence is returned, it automatically
98 selects the appropriate contextual return block for the calling con‐
99 text. So the previous example could be written even more cleanly 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
124 "LIST" and "VOID" blocks are always executed during the "return" state‐
125 ment. However, scalar return blocks ("SCALAR", "STR", "NUM", "BOOL",
126 etc.) blocks are not. Instead, returning any of scalar block types
127 causes the subroutine to return an object that lazily evaluates that
128 block only when the return value is used.
129
130 This means that returning a "SCALAR" block is a convenient way to
131 implement a subroutine with a lazy return value. For example:
132
133 sub digest {
134 return SCALAR {
135 my ($text) = @_;
136 md5($text);
137 }
138 }
139
140 my $digest = digest($text);
141
142 print $digest; # md5() called only when $digest used as string
143
144 To better document this usage, the "SCALAR" block has a synonym:
145 "LAZY".
146
147 sub digest {
148 return LAZY {
149 my ($text) = @_;
150 md5($text);
151 }
152 }
153
154 Active contextual return values
155
156 Once a return value has been lazily evaluated in a given context, the
157 resulting value is cached, and thereafter reused in that same context.
158
159 However, you can specify that, rather than being cached, the value
160 should be re-evaluated every time the value is used:
161
162 sub make_counter {
163 my $counter = 0;
164 return ACTIVE
165 SCALAR { ++$counter }
166 ARRAYREF { [1..$counter] }
167 }
168
169 my $idx = make_counter();
170
171 print "$idx\n"; # 1
172 print "$idx\n"; # 2
173 print "[@$idx]\n"; # [1 2]
174 print "$idx\n"; # 3
175 print "[@$idx]\n"; # [1 2 3]
176
177 Semi-lazy contextual return values
178
179 Sometimes, single or repeated lazy evaluation of a scalar return value
180 in different contexts isn't what you really want. Sometimes what you
181 really want is for the return value to be lazily evaluated once only
182 (the first time it's used in any context), and then for that first
183 value to be reused whenever the return value is subsequently reevalu‐
184 ated in any other context.
185
186 To get that behaviour, you can use the "FIXED" modifier, which causes
187 the return value to morph itself into the actual value the first time
188 it is used. For example:
189
190 sub lazy {
191 return
192 SCALAR { 42 }
193 ARRAYREF { [ 1, 2, 3 ] }
194 ;
195 }
196
197 my $lazy = lazy();
198 print $lazy + 1; # 43
199 print "@{$lazy}"; # 1 2 3
200
201 sub semilazy {
202 return FIXED
203 SCALAR { 42 }
204 ARRAYREF { [ 1, 2, 3 ] }
205 ;
206 }
207
208 my $semi = semilazy();
209 print $semi + 1; # 43
210 print "@{$semi}"; # die q{Can't use string ("42") as an ARRAY ref}
211
212 Finer distinctions of scalar context
213
214 Because the scalar values returned from a context sequence are lazily
215 evaluated, it becomes possible to be more specific about what kind of
216 scalar value should be returned: a boolean, a number, or a string. To
217 support those distinctions, Contextual::Return provides three extra
218 context blocks: "BOOL", "NUM", and "STR":
219
220 sub get_server_status {
221 my ($server_ID) = @_;
222
223 # Acquire server data somehow...
224 my %server_data = _ascertain_server_status($server_ID);
225
226 # Return different components of that data
227 # depending on call context...
228 return (
229 LIST { @server_data{ qw(name uptime load users) } }
230 BOOL { $server_data{uptime} > 0 }
231 NUM { $server_data{load} }
232 STR { "$server_data{name}: $server_data{uptime}" }
233 VOID { print "$server_data{load}\n" }
234 DEFAULT { croak q{Bad context! No biscuit!} }
235 );
236 }
237
238 With these in place, the object returned from a scalar-context call to
239 "get_server_status()" now behaves differently, depending on how it's
240 used. For example:
241
242 if ( my $status = get_server_status() ) { # True if uptime > 0
243 $load_distribution[$status]++; # Evaluates to load value
244 print "$status\n"; # Prints name: uptime
245 }
246
247 Referential contexts
248
249 The other major kind of scalar return value is a reference. Contex‐
250 tual::Return provides contextual return blocks that allow you to spec‐
251 ify what to (lazily) return when the return value of a subroutine is
252 used as a reference to a scalar ("SCALARREF {...}"), to an array
253 ("ARRAYREF {...}"), to a hash ("HASHREF {...}"), to a subroutine
254 ("CODEREF {...}"), or to a typeglob ("GLOBREF {...}").
255
256 For example, the server status subroutine shown earlier could be
257 extended to allow it to return a hash reference, thereby supporting
258 "named return values":
259
260 sub get_server_status {
261 my ($server_ID) = @_;
262
263 # Acquire server data somehow...
264 my %server_data = _ascertain_server_status($server_ID);
265
266 # Return different components of that data
267 # depending on call context...
268 return (
269 LIST { @server_data{ qw(name uptime load users) } }
270 BOOL { $server_data{uptime} > 0 }
271 NUM { $server_data{load} }
272 STR { "$server_data{name}: $server_data{uptime}" }
273 VOID { print "$server_data{load}\n" }
274 HASHREF { return \%server_data }
275 DEFAULT { croak q{Bad context! No biscuit!} }
276 );
277 }
278
279 # and later...
280
281 my $users = get_server_status->{users};
282
283 # or, lazily...
284
285 my $server = get_server_status();
286
287 print "$server->{name} load = $server->{load}\n";
288
289 Interpolative referential contexts
290
291 The "SCALARREF {...}" and "ARRAYREF {...}" context blocks are espe‐
292 cially useful when you need to interpolate a subroutine into strings.
293 For example, if you have a subroutine like:
294
295 sub get_todo_tasks {
296 return (
297 SCALAR { scalar @todo_list } # How many?
298 LIST { @todo_list } # What are they?
299 );
300 }
301
302 # and later...
303
304 print "There are ", scalar(get_todo_tasks()), " tasks:\n",
305 get_todo_tasks();
306
307 then you could make it much easier to interpolate calls to that subrou‐
308 tine by adding:
309
310 sub get_todo_tasks {
311 return (
312 SCALAR { scalar @todo_list } # How many?
313 LIST { @todo_list } # What are they?
314
315 SCALARREF { \scalar @todo_list } # Ref to how many
316 ARRAYREF { \@todo_list } # Ref to them
317 );
318 }
319
320 # and then...
321
322 print "There are ${get_todo_tasks()} tasks:\n@{get_todo_tasks()}";
323
324 In fact, this behaviour is so useful that it's the default. If you
325 don't provide an explicit "SCALARREF {...}" block, Contextual::Return
326 automatically provides an implicit one that simply returns a reference
327 to whatever would have been returned in scalar context. Likewise, if
328 no "ARRAYREF {...}" block is specified, the module supplies one that
329 returns the list-context return value wrapped up in an array reference.
330
331 So you could just write:
332
333 sub get_todo_tasks {
334 return (
335 SCALAR { scalar @todo_list } # How many?
336 LIST { @todo_list } # What are they?
337 );
338 }
339
340 # and still do this...
341
342 print "There are ${get_todo_tasks()} tasks:\n@{get_todo_tasks()}";
343
344 Fallback contexts
345
346 As the previous sections imply, the "BOOL {...}", "NUM {...}", "STR
347 {...}", and various "*REF {...}" blocks, are special cases of the gen‐
348 eral "SCALAR {...}" context block. If a subroutine is called in one of
349 these specialized contexts but does not use the corresponding context
350 block, then the more general "SCALAR {...}" block is used instead (if
351 it has been specified).
352
353 So, for example:
354
355 sub read_value_from {
356 my ($fh) = @_;
357
358 my $value = <$fh>;
359 chomp $value;
360
361 return (
362 BOOL { defined $value }
363 SCALAR { $value }
364 );
365 }
366
367 ensures that the "read_value_from()" subroutine returns true in boolean
368 contexts if the read was successful. But, because no specific "NUM
369 {...}" or "STR {...}" return behaviours were specified, the subroutine
370 falls back on using its generic "SCALAR {...}" block in all other
371 scalar contexts.
372
373 Another way to think about this behaviour is that the various kinds of
374 scalar context blocks form a hierarchy:
375
376 SCALAR
377 ^
378 ⎪
379 ⎪--< BOOL
380 ⎪
381 ⎪--< NUM
382 ⎪
383 `--< STR
384
385 Contextual::Return uses this hierarchical relationship to choose the
386 most specific context block available to handle any particular return
387 context, working its way up the tree from the specific type it needs,
388 to the more general type, if that's all that is available.
389
390 There are two slight complications to this picture. The first is that
391 Perl treats strings and numbers as interconvertable so the diagram (and
392 the Contextual::Return module) also has to allow these interconversions
393 as a fallback strategy:
394
395 SCALAR
396 ^
397 ⎪
398 ⎪--< BOOL
399 ⎪
400 ⎪--< NUM
401 ⎪ : ^
402 ⎪ v :
403 `--< STR
404
405 The dotted lines are meant to indicate that this intraconversion is
406 secondary to the main hierarchical fallback. That is, in a numeric con‐
407 text, a "STR {...}" block will only be used if there is no "NUM {...}"
408 block and no "SCALAR {...}" block. In other words, the generic context
409 type is always used in preference to string<->number conversion.
410
411 The second slight complication is that the above diagram only shows a
412 small part of the complete hierarchy of contexts supported by Contex‐
413 tual::Return. The full fallback hierarchy (including dotted intercon‐
414 versions) is:
415
416 DEFAULT
417 ^
418 ⎪
419 ⎪--< VOID
420 ⎪
421 `--< NONVOID
422 ^
423 ⎪
424 ⎪--< VALUE <..............
425 ⎪ ^ :
426 ⎪ ⎪ :
427 ⎪ ⎪--< SCALAR <.....:..
428 ⎪ ⎪ ^ :
429 ⎪ ⎪ ⎪ :
430 ⎪ ⎪ ⎪--< BOOL :
431 ⎪ ⎪ ⎪ :
432 ⎪ ⎪ ⎪--< NUM <..:..
433 ⎪ ⎪ ⎪ : ^ :
434 ⎪ ⎪ ⎪ v : :
435 ⎪ ⎪ `--< STR <....:..
436 ⎪ ⎪ :
437 ⎪ ⎪ .:
438 ⎪ `--< LIST ............. :
439 ⎪ : ^ :
440 ⎪ : : :
441 `--- REF : : :
442 ^ : : :
443 ⎪ v : :
444 ⎪--< ARRAYREF :
445 ⎪ .
446 ⎪--< SCALARREF .........
447 ⎪
448 ⎪--< HASHREF
449 ⎪
450 ⎪--< CODEREF
451 ⎪
452 ⎪--< GLOBREF
453 ⎪
454 `--< OBJREF
455
456 As before, each dashed arrow represents a fallback relationship. That
457 is, if the required context specifier isn't available, the arrows are
458 followed until a more generic one is found. The dotted arrows again
459 represent the interconversion of return values, which is attempted only
460 after the normal hierarchical fallback fails.
461
462 For example, if a subroutine is called in a context that expects a
463 scalar reference, but no "SCALARREF {...}" block is provided, then Con‐
464 textual::Return tries the following blocks in order:
465
466 REF {...}
467 NONVOID {...}
468 DEFAULT {...}
469 STR {...} (automatically taking a reference to the result)
470 NUM {...} (automatically taking a reference to the result)
471 SCALAR {...} (automatically taking a reference to the result)
472 VALUE {...} (automatically taking a reference to the result)
473
474 Likewise, in a list context, if there is no "LIST {...}" context block,
475 the module tries:
476
477 VALUE {...}
478 NONVOID {...}
479 DEFAULT {...}
480 ARRAYREF {...} (automatically dereferencing the result)
481 STR {...} (treating it as a list of one element)
482 NUM {...} (treating it as a list of one element)
483 SCALAR {...} (treating it as a list of one element)
484 VALUE {...} (treating it as a list of one element)
485
486 The more generic context blocks are especially useful for intercepting
487 unexpected and undesirable call contexts. For example, to turn off the
488 automatic scalar-ref and array-ref interpolative behaviour described in
489 "Interpolative referential contexts", you could intercept all referen‐
490 tial contexts using a generic "REF {...}" context block:
491
492 sub get_todo_tasks {
493 return (
494 SCALAR { scalar @todo_list } # How many?
495 LIST { @todo_list } # What are they?
496
497 REF { croak q{get_todo_task() can't be used as a reference} }
498 );
499 }
500
501 print 'There are ', get_todo_tasks(), '...'; # Still okay
502 print "There are ${get_todo_tasks()}..."; # Throws an exception
503
504 Failure contexts
505
506 Two of the most common ways to specify that a subroutine has failed are
507 to return a false value, or to throw an exception. The Contex‐
508 tual::Return module provides a mechanism that allows the subroutine
509 writer to support both of these mechanisms at the same time, by using
510 the "FAIL" specifier.
511
512 A return statement of the form:
513
514 return FAIL;
515
516 causes the surrounding subroutine to return "undef" (i.e. false) in
517 boolean contexts, and to throw an exception in any other context. For
518 example:
519
520 use Contextual::Return;
521
522 sub get_next_val {
523 my $next_val = <>;
524 return FAIL if !defined $next_val;
525 chomp $next_val;
526 return $next_val;
527 }
528
529 If the "return FAIL" statement is executed, it will either return false
530 in a boolean context:
531
532 if (my $val = get_next_val()) { # returns undef if no next val
533 print "[$val]\n";
534 }
535
536 or else throw an exception if the return value is used in any other
537 context:
538
539 print get_next_val(); # throws exception if no next val
540
541 my $next_val = get_next_val();
542 print "[$next_val]\n"; # throws exception if no next val
543
544 The exception that is thrown is of the form:
545
546 Call to main::get_next_val() failed at demo.pl line 42
547
548 but you can change that message by providing a block to the "FAIL",
549 like so:
550
551 return FAIL { "No more data" } if !defined $next_val;
552
553 in which case, the final value of the block becomes the exception mes‐
554 sage:
555
556 No more data at demo.pl line 42
557
558 Configurable failure contexts
559
560 The default "FAIL" behaviour--false in boolean context, fatal in all
561 others--works well in most situations, but violates the Platinum Rule
562 ("Do unto others as they would have done unto them").
563
564 So it may be user-friendlier if the user of a module is allowed decide
565 how the module's subroutines should behave on failure. For example, one
566 user might prefer that failing subs always return undef; another might
567 prefer that they always throw an exception; a third might prefer that
568 they always log the problem and return a special Failure object; whilst
569 a fourth user might want to get back 0 in scalar contexts, an empty
570 list in list contexts, and an exception everywhere else.
571
572 You could create a module that allows the user to specify all these
573 alternatives, like so:
574
575 package MyModule;
576 use Contextual::Return;
577 use Log::StdLog;
578
579 sub import {
580 my ($package, @args) = @_;
581
582 Contextual::Return::FAIL_WITH {
583 ':false' => sub { return undef },
584 ':fatal' => sub { croak @_ },
585 ':filed' => sub {
586 print STDLOG 'Sub ', (caller 1)[3], ' failed';
587 return Failure->new();
588 },
589 ':fussy' => sub {
590 SCALAR { undef }
591 LIST { () }
592 DEFAULT { croak @_ }
593 },
594 }, @args;
595 }
596
597 This configures Contextual::Return so that, instead of the usual false-
598 or-fatal semantics, every "return FAIL" within MyModule's namespace is
599 implemented by one of the four subroutines specified in the hash that
600 was passed to "FAIL_WITH".
601
602 Which of those four subs implements the "FAIL" is determined by the
603 arguments passed after the hash (i.e. by the contents of @args).
604 "FAIL_WITH" walks through that list of arguments and compares them
605 against the keys of the hash. If a key matches an argument, the corre‐
606 sponding value is used as the implementation of "FAIL". Note that, if
607 subsequent arguments also match a key, their subroutine overrides the
608 previously installed implementation, so only the final override has any
609 effect. Contextual::Return generates warnings when multiple overrides
610 are specified.
611
612 All of which mean that, if a user loaded the MyModule module like this:
613
614 use MyModule qw( :fatal other args here );
615
616 then every "FAIL" within MyModule would be reconfigured to throw an
617 exception in all circumstances, since the presence of the ':fatal' in
618 the argument list will cause "FAIL_WITH" to select the hash entry whose
619 key is ':fatal'.
620
621 On the other hand, if they loaded the module:
622
623 use MyModule qw( :fussy other args here );
624
625 then each "FAIL" within MyModule would return undef or empty list or
626 throw an exception, depending on context, since that's what the subrou‐
627 tine whose key is ':fussy' does.
628
629 Many people prefer module interfaces with a "flag =" value> format, and
630 "FAIL_WITH" supports this too. For example, if you wanted your module
631 to take a "-fail" flag, whose associated value could be any of "unde‐
632 fined", "exception", "logged", or "context", then you could implement
633 that simply by specifying the flag as the first argument (i.e. before
634 the hash) like so:
635
636 sub import {
637 my $package = shift;
638
639 Contextual::Return::FAIL_WITH -fail => {
640 'undefined' => sub { return undef },
641 'exception' => sub { croak @_ },
642 'logged' => sub {
643 print STDLOG 'Sub ', (caller 1)[3], ' failed';
644 return Failure->new();
645 },
646 'context' => sub {
647 SCALAR { undef }
648 LIST { () }
649 DEFAULT { croak @_ }
650 },
651 }, @_;
652
653 and then load the module:
654
655 use MyModule qw( other args here ), -fail=>'undefined';
656
657 or:
658
659 use MyModule qw( other args here ), -fail=>'exception';
660
661 In this case, "FAIL_WITH" scans the argument list for a pair of values:
662 its flag string, followed by some other selector value. Then it looks
663 up the selector value in the hash, and installs the corresponding sub‐
664 routine as its local "FAIL" handler.
665
666 If this "flagged" interface is used, the user of the module can also
667 specify their own handler directly, by passing a subroutine reference
668 as the selector value instead of a string:
669
670 use MyModule qw( other args here ), -fail=>sub{ die 'horribly'};
671
672 If this last example were used, any call to "FAIL" within MyModule
673 would invoke the specified anonymous subroutine (and hence throw a
674 'horribly' exception).
675
676 Note that, any overriding of a "FAIL" handler is specific to the names‐
677 pace and file from which the subroutine that calls "FAIL_WITH" is
678 itself called. Since "FAIL_WITH" is designed to be called from within a
679 module's "import()" subroutine, that generally means that the "FAIL"s
680 within a given module X are only overridden for the current namespace
681 within the particular file from module X is loaded. This means that two
682 separate pieces of code (in separate files or separate namespaces) can
683 each independently overide a module's "FAIL" behaviour, without inter‐
684 fering with each other.
685
686 Lvalue contexts
687
688 Recent versions of Perl offer (limited) support for lvalue subroutines:
689 subroutines that return a modifiable variable, rather than a simple
690 constant value.
691
692 Contextual::Return can make it easier to create such subroutines,
693 within the limitations imposed by Perl itself. The limitations that
694 Perl places on lvalue subs are:
695
696 1. The subroutine must be declared with an ":lvalue" attribute:
697
698 sub foo :lvalue {...}
699
700 2. The subroutine must not return via an explicit "return". Instead,
701 the last statement must evaluate to a variable, or must be a call
702 to another lvalue subroutine call.
703
704 my ($foo, $baz);
705
706 sub foo :lvalue {
707 $foo; # last statement evals to a var
708 }
709
710 sub bar :lvalue {
711 foo(); # last statement is lvalue sub call
712 }
713
714 sub baz :lvalue {
715 my ($arg) = @_;
716
717 $arg > 0 # last statement evals...
718 ? $baz # ...to a var
719 : bar(); # ...or to an lvalue sub call
720 }
721
722 Thereafter, any call to the lvalue subroutine produces a result that
723 can be assigned to:
724
725 baz(0) = 42; # same as: $baz = 42
726
727 baz(1) = 84; # same as: bar() = 84
728 # which is the same as: foo() = 84
729 # which is the same as: $foo = 84
730
731 Ultimately, every lvalue subroutine must return a scalar variable,
732 which is then used as the lvalue of the assignment (or whatever other
733 lvalue operation is applied to the subroutine call). Unfortunately,
734 because the subroutine has to return this variable before the assign‐
735 ment can take place, there is no way that a normal lvalue subroutine
736 can get access to the value that will eventually be assigned to its
737 return value.
738
739 This is occasionally annoying, so the Contextual::Return module offers
740 a solution: in addition to all the context blocks described above, it
741 provides three special contextual return blocks specifically for use in
742 lvalue subroutines: "LVALUE", "RVALUE", and "NVALUE".
743
744 Using these blocks you can specify what happens when an lvalue subrou‐
745 tine is used in lvalue and non-lvalue (rvalue) context. For example:
746
747 my $verbosity_level = 1;
748
749 # Verbosity values must be between 0 and 5...
750 sub verbosity :lvalue {
751 LVALUE { $verbosity_level = max(0, min($_, 5)) }
752 RVALUE { $verbosity_level }
753 }
754
755 The "LVALUE" block is executed whenever "verbosity" is called as an
756 lvalue:
757
758 verbosity() = 7;
759
760 The block has access to the value being assigned, which is passed to it
761 as $_. So, in the above example, the assigned value of 7 would be
762 aliased to $_ within the "LVALUE" block, would be reduced to 5 by the
763 "min-of-max" expression, and then assigned to $verbosity_level.
764
765 (If you need to access the caller's $_, it's also still available: as
766 $CALLER::_.)
767
768 When the subroutine isn't used as an lvalue:
769
770 print verbosity();
771
772 the "RVALUE" block is executed instead and its final value returned.
773 Within an "RVALUE" block you can use any of the other features of Con‐
774 textual::Return. For example:
775
776 sub verbosity :lvalue {
777 LVALUE { $verbosity_level = int max(0, min($_, 5)) }
778 RVALUE {
779 NUM { $verbosity_level }
780 STR { $description[$verbosity_level] }
781 BOOL { $verbosity_level > 2 }
782 }
783 }
784
785 but the context sequence must be nested inside an "RVALUE" block.
786
787 You can also specify what an lvalue subroutine should do when it is
788 used neither as an lvalue nor as an rvalue (i.e. in void context), by
789 using an "NVALUE" block:
790
791 sub verbosity :lvalue {
792 my ($level) = @_;
793
794 NVALUE { $verbosity_level = int max(0, min($level, 5)) }
795 LVALUE { $verbosity_level = int max(0, min($_, 5)) }
796 RVALUE {
797 NUM { $verbosity_level }
798 STR { $description[$verbosity_level] }
799 BOOL { $verbosity_level > 2 }
800 }
801 }
802
803 In this example, a call to "verbosity()" in void context sets the ver‐
804 bosity level to whatever argument is passed to the subroutine:
805
806 verbosity(1);
807
808 Note that you cannot get the same effect by nesting a "VOID" block
809 within an "RVALUE" block:
810
811 LVALUE { $verbosity_level = int max(0, min($_, 5)) }
812 RVALUE {
813 NUM { $verbosity_level }
814 STR { $description[$verbosity_level] }
815 BOOL { $verbosity_level > 2 }
816 VOID { $verbosity_level = $level } # Wrong!
817 }
818
819 That's because, in a void context the return value is never evaluated,
820 so it is never treated as an rvalue, which means the "RVALUE" block
821 never executes.
822
823 Result blocks
824
825 Occasionally, it's convenient to calculate a return value before the
826 end of a contextual return block. For example, you may need to clean up
827 external resources involved in the calculation after it's complete.
828 Typically, this requirement produces a slightly awkward code sequence
829 like this:
830
831 return
832 VALUE {
833 $db->start_work();
834 my $result = $db->retrieve_query($query);
835 $db->commit();
836 $result;
837 }
838
839 Such code sequences become considerably more awkward when you want the
840 return value to be context sensitive, in which case you have to write
841 either:
842
843 return
844 LIST {
845 $db->start_work();
846 my @result = $db->retrieve_query($query);
847 $db->commit();
848 @result;
849 }
850 SCALAR {
851 $db->start_work();
852 my $result = $db->retrieve_query($query);
853 $db->commit();
854 $result;
855 }
856
857 or, worse:
858
859 return
860 VALUE {
861 $db->start_work();
862 my $result = LIST ? [$db->retrieve_query($query)]
863 : $db->retrieve_query($query);
864 $db->commit();
865 LIST ? @{$result} : $result;
866 }
867
868 To avoid these infelicities, Contextual::Return provides a second way
869 of setting the result of a context block; a way that doesn't require
870 that the result be the last statement in the block:
871
872 return
873 LIST {
874 $db->start_work();
875 RESULT { $db->retrieve_query($query) };
876 $db->commit();
877 }
878 SCALAR {
879 $db->start_work();
880 RESULT { $db->retrieve_query($query) };
881 $db->commit();
882 }
883
884 The presence of a "RESULT" block inside a contextual return block
885 causes that block to return the value of the final statement of the
886 "RESULT" block as the handler's return value, rather than returning the
887 value of the handler's own final statement. In other words, the pres‐
888 ence of a "RESULT" block overrides the normal return value of a context
889 handler.
890
891 Better still, the "RESULT" block always evaluates its final statement
892 in the same context as the surrounding "return", so you can just write:
893
894 return
895 VALUE {
896 $db->start_work();
897 RESULT { $db->retrieve_query($query) };
898 $db->commit();
899 }
900
901 and the "retrieve_query()" method will be called in the appropriate
902 context in all cases.
903
904 A "RESULT" block can appear anywhere inside any contextual return
905 block, but may not be used outside a context block. That is, this is an
906 error:
907
908 if ($db->closed) {
909 RESULT { undef }; # Error: not in a context block
910 }
911 return
912 VALUE {
913 $db->start_work();
914 RESULT { $db->retrieve_query($query) };
915 $db->commit();
916 }
917
918 Post-handler clean-up
919
920 If a subroutine uses an external resource, it's often necessary to
921 close or clean-up that resource after the subroutine ends...regardless
922 of whether the subroutine exits normally or via an exception.
923
924 Typically, this is done by encapsulating the resource in a lexically
925 scoped object whose constructor does the clean-up. However, if the
926 clean-up doesn't involve deallocation of an object (as in the
927 "$db->commit()" example in the previous section), it can be annoying to
928 have to create a class and allocate a container object, merely to medi‐
929 ate the clean-up.
930
931 To make it easier to manage such resources, Contextual::Return supplies
932 a special labelled block: the "RECOVER" block. If a "RECOVER" block is
933 specified as part of a contextual return sequence, that block is exe‐
934 cuted after any context handler, even if the context handler exits via
935 an exception.
936
937 So, for example, you could implement a simple commit-or-revert policy
938 like so:
939
940 return
941 LIST { $db->retrieve_all($query) }
942 SCALAR { $db->retrieve_next($query) }
943 RECOVER {
944 if ($@) {
945 $db->revert();
946 }
947 else {
948 $db->commit();
949 }
950 }
951
952 The presence of a "RECOVER" block also intercepts all exceptions thrown
953 in any other context block in the same contextual return sequence. Any
954 such exception is passed into the "RECOVER" block in the usual manner:
955 via the $@ variable. The exception may be rethrown out of the "RECOVER"
956 block by calling "die":
957
958 return
959 LIST { $db->retrieve_all($query) }
960 DEFAULT { croak "Invalid call (not in list context)" }
961 RECOVER {
962 die $@ if $@; # Propagate any exception
963 $db->commit(); # Otherwise commit the changes
964 }
965
966 A "RECOVER" block can also access or replace the returned value, by
967 invoking a "RESULT" block. For example:
968
969 return
970 LIST { attempt_to_generate_list_for(@_) }
971 SCALAR { attempt_to_generate_count_for(@_) }
972 RECOVER {
973 if ($@) { # On any exception...
974 RESULT { undef } # ...return undef
975 }
976 }
977
979 Context tests
980
981 "LIST()"
982 Returns true if the current subroutine was called in list context.
983 A cleaner way of writing: "wantarray()"
984
985 "SCALAR()"
986 Returns true if the current subroutine was called in scalar con‐
987 text. A cleaner way of writing: "defined wantarray() && ! wantar‐
988 ray()"
989
990 "VOID()"
991 Returns true if the current subroutine was called in void context.
992 A cleaner way of writing: "!defined wantarray()"
993
994 "NONVOID()"
995 Returns true if the current subroutine was called in list or scalar
996 context. A cleaner way of writing: "defined wantarray()"
997
998 Standard contexts
999
1000 "LIST {...}"
1001 The block specifies what the context sequence should evaluate to
1002 when called in list context.
1003
1004 "SCALAR {...}"
1005 The block specifies what the context sequence should evaluate to in
1006 scalar contexts, unless some more-specific specifier scalar context
1007 specifier (see below) also occurs in the same context sequence.
1008
1009 "VOID {...}"
1010 The block specifies what the context sequence should do when called
1011 in void context.
1012
1013 Scalar value contexts
1014
1015 "BOOL {...}"
1016 The block specifies what the context sequence should evaluate to
1017 when treated as a boolean value.
1018
1019 "NUM {...}"
1020 The block specifies what the context sequence should evaluate to
1021 when treated as a numeric value.
1022
1023 "STR {...}"
1024 The block specifies what the context sequence should evaluate to
1025 when treated as a string value.
1026
1027 "LAZY {...}"
1028 Another name for "SCALAR {...}". Usefully self-documenting when the
1029 primary purpose of the contextual return is to defer evaluation of
1030 the return value until it's actually required.
1031
1032 Scalar reference contexts
1033
1034 "SCALARREF {...}"
1035 The block specifies what the context sequence should evaluate to
1036 when treated as a reference to a scalar.
1037
1038 "ARRAYREF {...}"
1039 The block specifies what the context sequence should evaluate to
1040 when treated as a reference to an array.
1041
1042 "HASHREF {...}"
1043 The block specifies what the context sequence should evaluate to
1044 when treated as a reference to a hash.
1045
1046 Note that a common error here is to write:
1047
1048 HASHREF { a=>1, b=>2, c=>3 }
1049
1050 The curly braces there are a block, not a hash constructor, so the
1051 block doesn't return a hash reference and the interpreter throws an
1052 exception. What's needed is:
1053
1054 HASHREF { {a=>1, b=>2, c=>3} }
1055
1056 in which the inner braces are a hash constructor.
1057
1058 "CODEREF {...}"
1059 The block specifies what the context sequence should evaluate to
1060 when treated as a reference to a subroutine.
1061
1062 "GLOBREF {...}"
1063 The block specifies what the context sequence should evaluate to
1064 when treated as a reference to a typeglob.
1065
1066 "OBJREF {...}"
1067 The block specifies what the context sequence should evaluate to
1068 when treated as a reference to an object.
1069
1070 Generic contexts
1071
1072 "VALUE {...}"
1073 The block specifies what the context sequence should evaluate to
1074 when treated as a non-referential value (as a boolean, numeric,
1075 string, scalar, or list). Only used if there is no more-specific
1076 value context specifier in the context sequence.
1077
1078 "REF {...}"
1079 The block specifies what the context sequence should evaluate to
1080 when treated as a reference of any kind. Only used if there is no
1081 more-specific referential context specifier in the context
1082 sequence.
1083
1084 "NONVOID {...}"
1085 The block specifies what the context sequence should evaluate to
1086 when used in a non-void context of any kind. Only used if there is
1087 no more-specific context specifier in the context sequence.
1088
1089 "DEFAULT {...}"
1090 The block specifies what the context sequence should evaluate to
1091 when used in a void or non-void context of any kind. Only used if
1092 there is no more-specific context specifier in the context
1093 sequence.
1094
1095 Failure context
1096
1097 "FAIL"
1098 This block is executed unconditionally and is used to indicate
1099 failure. In a Boolean context it return false. In all other con‐
1100 texts it throws an exception consisting of the final evaluated
1101 value of the block.
1102
1103 That is, using "FAIL":
1104
1105 return
1106 FAIL { "Could not defenestrate the widget" }
1107
1108 is exactly equivalent to writing:
1109
1110 return
1111 BOOL { 0 }
1112 DEFAULT { croak "Could not defenestrate the widget" }
1113
1114 except that the reporting of errors is a little smarter under
1115 "FAIL".
1116
1117 If "FAIL" is called without specifying a block:
1118
1119 return FAIL;
1120
1121 it is equivalent to:
1122
1123 return FAIL { croak "Call to <subname> failed" }
1124
1125 (where "<subname>" is replaced with the name of the surrounding
1126 subroutine).
1127
1128 Note that, because "FAIL" implicitly covers every possible return
1129 context, it cannot be chained with other context specifiers.
1130
1131 "Contextual::Return::FAIL_WITH"
1132 This subroutine is not exported, but may be called directly to
1133 reconfigure "FAIL" behaviour in the caller's namespace.
1134
1135 The subroutine is called with an optional string (the flag), fol‐
1136 lowed by a mandatory hash reference (the configurations hash), fol‐
1137 lowed by a list of zero-or-more strings (the selector list). The
1138 values of the configurations hash must all be subroutine refer‐
1139 ences.
1140
1141 If the optional flag is specified, "FAIL_WITH" searches the selec‐
1142 tor list looking for that string, then uses the following item in
1143 the selector list as its selector value. If that selector value is
1144 a string, "FAIL_WITH" looks up that key in the hash, and installs
1145 the corresponding subroutine as the namespace's "FAIL" handler (an
1146 exception is thrown if the selector string is not a valid key of
1147 the configurations hash). If the selector value is a subroutine
1148 reference, "FAIL_WITH" installs that subroutine as the "FAIL" han‐
1149 dler.
1150
1151 If the optional flag is not specified, "FAIL_WITH" searches the
1152 entire selector list looking for the last element that matches any
1153 key in the configurations hash. It then looks up that key in the
1154 hash, and installs the corresponding subroutine as the namespace's
1155 "FAIL" handler.
1156
1157 See "Configurable failure contexts" for examples of using this fea‐
1158 ture.
1159
1160 Lvalue contexts
1161
1162 "LVALUE"
1163 This block is executed when the result of an ":lvalue" subroutine
1164 is assigned to. The assigned value is passed to the block as $_. To
1165 access the caller's $_ value, use $CALLER::_.
1166
1167 "RVALUE"
1168 This block is executed when the result of an ":lvalue" subroutine
1169 is used as an rvalue. The final value that is evaluated in the
1170 block becomes the rvalue.
1171
1172 "NVALUE"
1173 This block is executed when an ":lvalue" subroutine is evaluated in
1174 void context.
1175
1176 Explicit result blocks
1177
1178 "RESULT"
1179 This block may only appear inside a context handler block. It
1180 causes the surrounding handler to return the final value of the
1181 "RESULT"'s block, rather than the final value of the handler's own
1182 block. This override occurs regardless of the location to the
1183 "RESULT" block within the handler.
1184
1185 Recovery blocks
1186
1187 "RECOVER"
1188 If present in a context return sequence, this block grabs control
1189 after any context handler returns or exits via an exception. If an
1190 exception was thrown it is passed to the "RECOVER" block via the $@
1191 variable.
1192
1193 Modifiers
1194
1195 "FIXED"
1196 This specifies that the scalar value will only be evaluated once,
1197 the first time it is used, and that the value will then morph into
1198 that evaluated value.
1199
1200 "ACTIVE"
1201 This specifies that the scalar value's originating block will be
1202 re- evaluated every time the return value is used.
1203
1205 Can't call %s in %s context";
1206 The subroutine you called uses a contextual return, but doesn't
1207 specify what to return in the particular context in which you
1208 called it. You either need to change the context in which you're
1209 calling the subroutine, or else add a context block corresponding
1210 to the offending context (or perhaps a "DEFAULT {...}" block).
1211
1212 %s can't return a %s reference";
1213 You called the subroutine in a context that expected to get back a
1214 reference of some kind but the subroutine didn't specify the corre‐
1215 sponding "SCALARREF", "ARRAYREF", "HASHREF", "CODEREF", "GLOBREF",
1216 or generic "REF", "NONVOID", or "DEFAULT" handlers. You need to
1217 specify the appropriate one of these handlers in the subroutine.
1218
1219 Can't call method '%s' on %s value returned by %s";
1220 You called the subroutine and then tried to call a method on the
1221 return value, but the subroutine returned a classname or object
1222 that doesn't have that method. This probably means that the subrou‐
1223 tine didn't return the classname or object you expected. Or perhaps
1224 you need to specify an "OBJREF {...}" context block.
1225
1226 Can't install two %s handlers
1227 You attempted to specify two context blocks of the same name in the
1228 same return context, which is ambiguous. For example:
1229
1230 sub foo: lvalue {
1231 LVALUE { $foo = $_ }
1232 RVALUE { $foo }
1233 LVALUE { $foo = substr($_,1,10) }
1234 }
1235
1236 or:
1237
1238 sub bar {
1239 return
1240 BOOL { 0 }
1241 NUM { 1 }
1242 STR { "two" }
1243 BOOL { 1 };
1244 }
1245
1246 Did you cut-and-paste wrongly, or mislabel one of the blocks?
1247
1248 Expected a %s block after the %s block but found instead: %s
1249 If you specify any of "LVALUE", "RVALUE", or "NVALUE", then you can
1250 only specify "LVALUE", "RVALUE", or "NVALUE" blocks in the same
1251 return context. If you need to specify other contexts (like
1252 "BOOL", or "STR", or "REF", etc.), put them inside an "RVALUE"
1253 block. See "Lvalue contexts" for an example.
1254
1255 Call to %s failed at %s.
1256 This is the default exception that a "FAIL" throws in a non-scalar
1257 context. Which means that the subroutine you called has signalled
1258 failure by throwing an exception, and you didn't catch that excep‐
1259 tion. You should either put the call in an "eval {...}" block or
1260 else call the subroutine in boolean context instead.
1261
1262 Call to %s failed at %s. Failure value used at %s
1263 This is the default exception that a "FAIL" throws when a failure
1264 value is captured in a scalar variable and later used in a non-
1265 boolean context. That means that the subroutine you called must
1266 have failed, and you didn't check the return value for that fail‐
1267 ure, so when you tried to use that invalid value it killed your
1268 program. You should either put the original call in an "eval {...}"
1269 or else test the return value in a boolean context and avoid using
1270 it if it's false.
1271
1272 Usage: FAIL_WITH $flag_opt, \%selector, @args
1273 The "FAIL_WITH" subroutine expects an optional flag, followed by a
1274 reference to a configuration hash, followed by a list or selector
1275 arguments. You gave it something else. See "Configurable Failure
1276 Contexts".
1277
1278 Selector values must be sub refs
1279 You passed a configuration hash to "FAIL_WITH" that specified non-
1280 subroutines as possible "FAIL" handlers. Since non-subroutines
1281 can't possibly be handlers, maybe you forgot the "sub" keyword
1282 somewhere?
1283
1284 Invalid option: %s => %s
1285 The "FAIL_WITH" subroutine was passed a flag/selector pair, but the
1286 selector was not one of those allowed by the configuration hash.
1287
1288 FAIL handler for package %s redefined
1289 A warning that the "FAIL" handler for a particular package was
1290 reconfigured more than once. Typically that's because the module
1291 was loaded in two places with difference configurations specified.
1292 You can't reasonably expect two different sets of behaviours from
1293 the one module within the one namespace.
1294
1296 Contextual::Return requires no configuration files or environment vari‐
1297 ables.
1298
1300 Requires version.pm and Want.pm.
1301
1303 None reported.
1304
1306 No bugs have been reported.
1307
1309 Damian Conway "<DCONWAY@cpan.org>"
1310
1312 Copyright (c) 2005-2006, Damian Conway "<DCONWAY@cpan.org>". All rights
1313 reserved.
1314
1315 This module is free software; you can redistribute it and/or modify it
1316 under the same terms as Perl itself.
1317
1319 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
1320 FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT
1321 WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER
1322 PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND,
1323 EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1324 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
1325 ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
1326 YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
1327 NECESSARY SERVICING, REPAIR, OR CORRECTION.
1328
1329 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
1330 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
1331 REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE
1332 TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CON‐
1333 SEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFT‐
1334 WARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED
1335 INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF
1336 THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER
1337 OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
1338
1339
1340
1341perl v5.8.8 2007-03-29 Contextual::Return(3)