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