1Want(3) User Contributed Perl Documentation Want(3)
2
3
4
6 Want - A generalisation of "wantarray"
7
9 use Want;
10 sub foo :lvalue {
11 if (want(qw'LVALUE ASSIGN')) {
12 print "We have been assigned ", want('ASSIGN');
13 lnoreturn;
14 }
15 elsif (want('LIST')) {
16 rreturn (1, 2, 3);
17 }
18 elsif (want('BOOL')) {
19 rreturn 0;
20 }
21 elsif (want(qw'SCALAR !REF')) {
22 rreturn 23;
23 }
24 elsif (want('HASH')) {
25 rreturn { foo => 17, bar => 23 };
26 }
27 return; # You have to put this at the end to keep the compiler happy
28 }
29
31 This module generalises the mechanism of the wantarray function,
32 allowing a function to determine in some detail how its return value is
33 going to be immediately used.
34
35 Top-level contexts:
36 The three kinds of top-level context are well known:
37
38 VOID
39 The return value is not being used in any way. It could be an
40 entire statement like "foo();", or the last component of a compound
41 statement which is itself in void context, such as "$test ||
42 foo();"n. Be warned that the last statement of a subroutine will be
43 in whatever context the subroutine was called in, because the
44 result is implicitly returned.
45
46 SCALAR
47 The return value is being treated as a scalar value of some sort:
48
49 my $x = foo();
50 $y += foo();
51 print "123" x foo();
52 print scalar foo();
53 warn foo()->{23};
54 ...etc...
55
56 LIST
57 The return value is treated as a list of values:
58
59 my @x = foo();
60 my ($x) = foo();
61 () = foo(); # even though the results are discarded
62 print foo();
63 bar(foo()); # unless the bar subroutine has a prototype
64 print @hash{foo()}; # (hash slice)
65 ...etc...
66
67 Lvalue subroutines:
68 The introduction of lvalue subroutines in Perl 5.6 has created a new
69 type of contextual information, which is independent of those listed
70 above. When an lvalue subroutine is called, it can either be called in
71 the ordinary way (so that its result is treated as an ordinary value,
72 an rvalue); or else it can be called so that its result is considered
73 updatable, an lvalue.
74
75 These rather arcane terms (lvalue and rvalue) are easier to remember if
76 you know why they are so called. If you consider a simple assignment
77 statement "left = right", then the left-hand side is an lvalue and the
78 right-hand side is an rvalue.
79
80 So (for lvalue subroutines only) there are two new types of context:
81
82 RVALUE
83 The caller is definitely not trying to assign to the result:
84
85 foo();
86 my $x = foo();
87 ...etc...
88
89 If the sub is declared without the ":lvalue" attribute, then it
90 will always be in RVALUE context.
91
92 If you need to return values from an lvalue subroutine in RVALUE
93 context, you should use the "rreturn" function rather than an
94 ordinary "return". Otherwise you'll probably get a compile-time
95 error in perl 5.6.1 and later.
96
97 LVALUE
98 Either the caller is directly assigning to the result of the sub
99 call:
100
101 foo() = $x;
102 foo() = (1, 1, 2, 3, 5, 8);
103
104 or the caller is making a reference to the result, which might be
105 assigned to later:
106
107 my $ref = \(foo()); # Could now have: $$ref = 99;
108
109 # Note that this example imposes LIST context on the sub call.
110 # So we're taking a reference to the first element to be
111 # returned _in list context_.
112 # If we want to call the function in scalar context, we can
113 # do it like this:
114 my $ref = \(scalar foo());
115
116 or else the result of the function call is being used as part of
117 the argument list for another function call:
118
119 bar(foo()); # Will *always* call foo in lvalue context,
120 # (provided that foo is an C<:lvalue> sub)
121 # regardless of what bar actually does.
122
123 The reason for this last case is that bar might be a sub which
124 modifies its arguments. They're rare in contemporary Perl code, but
125 perfectly possible:
126
127 sub bar {
128 $_[0] = 23;
129 }
130
131 (This is really a throwback to Perl 4, which didn't support
132 explicit references.)
133
134 Assignment context:
135 The commonest use of lvalue subroutines is with the assignment
136 statement:
137
138 size() = 12;
139 (list()) = (1..10);
140
141 A useful motto to remember when thinking about assignment statements is
142 context comes from the left. Consider code like this:
143
144 my ($x, $y, $z);
145 sub list () :lvalue { ($x, $y, $z) }
146 list = (1, 2, 3);
147 print "\$x = $x; \$y = $y; \$z = $z\n";
148
149 This prints "$x = ; $y = ; $z = 3", which may not be what you were
150 expecting. The reason is that the assignment is in scalar context, so
151 the comma operator is in scalar context too, and discards all values
152 but the last. You can fix it by writing "(list) = (1,2,3);" instead.
153
154 If your lvalue subroutine is used on the left of an assignment
155 statement, it's in ASSIGN context. If ASSIGN is the only argument to
156 "want()", then it returns a reference to an array of the value(s) of
157 the right-hand side.
158
159 In this case, you should return with the "lnoreturn" function, rather
160 than an ordinary "return".
161
162 This makes it very easy to write lvalue subroutines which do clever
163 things:
164
165 use Want;
166 use strict;
167 sub backstr :lvalue {
168 if (want(qw'LVALUE ASSIGN')) {
169 my ($a) = want('ASSIGN');
170 $_[0] = reverse $a;
171 lnoreturn;
172 }
173 elsif (want('RVALUE')) {
174 rreturn scalar reverse $_[0];
175 }
176 else {
177 carp("Not in ASSIGN context");
178 }
179 return
180 }
181
182 print "foo -> ", backstr("foo"), "\n"; # foo -> oof
183 backstr(my $robin) = "nibor";
184 print "\$robin is now $robin\n"; # $robin is now robin
185
186 Notice that you need to put a (meaningless) return statement at the end
187 of the function, otherwise you will get the error Can't modify non-
188 lvalue subroutine call in lvalue subroutine return.
189
190 The only way to write that "backstr" function without using Want is to
191 return a tied variable which is tied to a custom class.
192
193 Reference context:
194 Sometimes in scalar context the caller is expecting a reference of some
195 sort to be returned:
196
197 print foo()->(); # CODE reference expected
198 print foo()->{bar}; # HASH reference expected
199 print foo()->[23]; # ARRAY reference expected
200 print ${foo()}; # SCALAR reference expected
201 print foo()->bar(); # OBJECT reference expected
202
203 my $format = *{foo()}{FORMAT} # GLOB reference expected
204
205 You can check this using conditionals like "if (want('CODE'))". There
206 is also a function "wantref()" which returns one of the strings "CODE",
207 "HASH", "ARRAY", "GLOB", "SCALAR" or "OBJECT"; or the empty string if a
208 reference is not expected.
209
210 Because "want('SCALAR')" is already used to select ordinary scalar
211 context, you have to use "want('REFSCALAR')" to find out if a SCALAR
212 reference is expected. Or you could use "want('REF') eq 'SCALAR'" of
213 course.
214
215 Be warned that "want('ARRAY')" is a very different thing from
216 "wantarray()".
217
218 Item count
219 Sometimes in list context the caller is expecting a particular number
220 of items to be returned:
221
222 my ($x, $y) = foo(); # foo is expected to return two items
223
224 If you pass a number to the "want" function, then it will return true
225 or false according to whether at least that many items are wanted. So
226 if we are in the definition of a sub which is being called as above,
227 then:
228
229 want(1) returns true
230 want(2) returns true
231 want(3) returns false
232
233 Sometimes there is no limit to the number of items that might be used:
234
235 my @x = foo();
236 do_something_with( foo() );
237
238 In this case, want(2), "want(100)", "want(1E9)" and so on will all
239 return true; and so will "want('Infinity')".
240
241 The "howmany" function can be used to find out how many items are
242 wanted. If the context is scalar, then want(1) returns true and
243 "howmany()" returns 1. If you want to check whether your result is
244 being assigned to a singleton list, you can say "if (want('LIST', 1)) {
245 ... }".
246
247 Boolean context
248 Sometimes the caller is only interested in the truth or falsity of a
249 function's return value:
250
251 if (everything_is_okay()) {
252 # Carry on
253 }
254
255 print (foo() ? "ok\n" : "not ok\n");
256
257 In the following example, all subroutine calls are in BOOL context:
258
259 my $x = ( (foo() && !bar()) xor (baz() || quux()) );
260
261 Boolean context, like the reference contexts above, is considered to be
262 a subcontext of SCALAR.
263
265 want(SPECIFIERS)
266 This is the primary interface to this module, and should suffice
267 for most purposes. You pass it a list of context specifiers, and
268 the return value is true whenever all of the specifiers hold.
269
270 want('LVALUE', 'SCALAR'); # Are we in scalar lvalue context?
271 want('RVALUE', 3); # Are at least three rvalues wanted?
272 want('ARRAY'); # Is the return value used as an array ref?
273
274 You can also prefix a specifier with an exclamation mark to
275 indicate that you don't want it to be true
276
277 want(2, '!3'); # Caller wants exactly two items.
278 want(qw'REF !CODE !GLOB'); # Expecting a reference that
279 # isn't a CODE or GLOB ref.
280 want(100, '!Infinity'); # Expecting at least 100 items,
281 # but there is a limit.
282
283 If the REF keyword is the only parameter passed, then the type of
284 reference will be returned. This is just a synonym for the
285 "wantref" function: it's included because you might find it useful
286 if you don't want to pollute your namespace by importing several
287 functions, and to conform to Damian Conway's suggestion in RFC 21.
288
289 Finally, the keyword COUNT can be used, provided that it's the only
290 keyword you pass. Mixing COUNT with other keywords is an error.
291 This is a synonym for the "howmany" function.
292
293 A full list of the permitted keyword is in the ARGUMENTS section
294 below.
295
296 rreturn
297 Use this function instead of "return" from inside an lvalue
298 subroutine when you know that you're in RVALUE context. If you try
299 to use a normal "return", you'll get a compile-time error in Perl
300 5.6.1 and above unless you return an lvalue. (Note: this is no
301 longer true in Perl 5.16, where an ordinary return will once again
302 work.)
303
304 lnoreturn
305 Use this function instead of "return" from inside an lvalue
306 subroutine when you're in ASSIGN context and you've used
307 "want('ASSIGN')" to carry out the appropriate action.
308
309 If you use "rreturn" or "lnoreturn", then you have to put a bare
310 "return;" at the very end of your lvalue subroutine, in order to
311 stop the Perl compiler from complaining. Think of it as akin to the
312 "1;" that you have to put at the end of a module. (Note: this is no
313 longer true in Perl 5.16.)
314
315 howmany()
316 Returns the expectation count, i.e. the number of items expected.
317 If the expectation count is undefined, that indicates that an
318 unlimited number of items might be used (e.g. the return value is
319 being assigned to an array). In void context the expectation count
320 is zero, and in scalar context it is one.
321
322 The same as "want('COUNT')".
323
324 wantref()
325 Returns the type of reference which the caller is expecting, or the
326 empty string if the caller isn't expecting a reference immediately.
327
328 The same as "want('REF')".
329
331 use Carp 'croak';
332 use Want 'howmany';
333 sub numbers {
334 my $count = howmany();
335 croak("Can't make an infinite list") if !defined($count);
336 return (1..$count);
337 }
338 my ($one, $two, $three) = numbers();
339
340
341 use Want 'want';
342 sub pi () {
343 if (want('ARRAY')) {
344 return [3, 1, 4, 1, 5, 9];
345 }
346 elsif (want('LIST')) {
347 return (3, 1, 4, 1, 5, 9);
348 }
349 else {
350 return 3;
351 }
352 }
353 print pi->[2]; # prints 4
354 print ((pi)[3]); # prints 1
355
357 The permitted arguments to the "want" function are listed below. The
358 list is structured so that sub-contexts appear below the context that
359 they are part of.
360
361 · VOID
362
363 · SCALAR
364
365 · REF
366
367 · REFSCALAR
368
369 · CODE
370
371 · HASH
372
373 · ARRAY
374
375 · GLOB
376
377 · OBJECT
378
379 · BOOL
380
381 · LIST
382
383 · COUNT
384
385 · <number>
386
387 · Infinity
388
389 · LVALUE
390
391 · ASSIGN
392
393 · RVALUE
394
396 The "want" and "rreturn" functions are exported by default. The
397 "wantref" and/or "howmany" functions can also be imported:
398
399 use Want qw'want howmany';
400
401 If you don't import these functions, you must qualify their names as
402 (e.g.) "Want::wantref".
403
405 This module is still under development, and the public interface may
406 change in future versions. The "want" function can now be regarded as
407 stable.
408
409 I'd be interested to know how you're using this module.
410
412 There are two different levels of BOOL context. Pure boolean context
413 occurs in conditional expressions, and the operands of the "xor" and
414 "!"/"not" operators. Pure boolean context also propagates down through
415 the "&&" and "||" operators.
416
417 However, consider an expression like "my $x = foo() && "yes"". The
418 subroutine is called in pseudo-boolean context - its return value isn't
419 entirely ignored, because the undefined value, the empty string and the
420 integer 0 are all false.
421
422 At the moment "want('BOOL')" is true in either pure or pseudo boolean
423 context. Let me know if this is a problem.
424
426 * Doesn't work from inside a tie-handler.
427
429 Robin Houston, <robin@cpan.org>
430
431 Thanks to Damian Conway for encouragement and good suggestions, and
432 Father Chrysostomos for a patch.
433
435 · "wantarray" in perlfunc
436
437 · Perl6 RFC 21, by Damian Conway. http://dev.perl.org/rfc/21.html
438
440 Copyright (c) 2001-2012, Robin Houston. All Rights Reserved. This
441 module is free software. It may be used, redistributed and/or modified
442 under the same terms as Perl itself.
443
444
445
446perl v5.30.0 2019-07-26 Want(3)