Want(3pm)
β¨ NAME β¨
Want β a generalisation of wantarray π
(this is Want(3pm), straight outta the User Contributed Perl Documentation, and yes bestie it ate)
π SYNOPSIS π
okay so here's the vibe, no cap:
use Want;
sub foo :lvalue {
if (want(qw'LVALUE ASSIGN')) {
print "We have been assigned ", want('ASSIGN');
lnoreturn;
}
elsif (want('LIST')) {
rreturn (1, 2, 3);
}
elsif (want('BOOL')) {
rreturn 0;
}
elsif (want(qw'SCALAR !REF')) {
rreturn 23;
}
elsif (want('HASH')) {
rreturn { foo => 17, bar => 23 };
}
return; # You have to put this at the end to keep the compiler happy
}
that return; at the end? it's giving "mandatory accessory", don't skip it π«Ά
π DESCRIPTION π
so this module is basically wantarray but with main character energy β¨ it takes the whole mechanism of the wantarray function and generalises it, so a function can figure out, in actual detail, how its return value is about to be immediately used. like, not just "am I in list or scalar" but the whole situation. obsessed.
π Top-level contexts π
the three kinds of top-level context are, like, the well-known ones everyone knows:
VOID
the return value isn't being used at all. literally nothing. it could be a whole entire statement like foo();, or it could be the last component of a compound statement that is itself in void context, like $test || foo();"n. β οΈ be warned though: the last statement of a subroutine is gonna be in whatever context the subroutine was called in, because the result gets implicitly returned. sneaky.
SCALAR
the return value is being treated as a scalar value of some sort:
my $x = foo();
$y += foo();
print "123" x foo();
print scalar foo();
warn foo()->{23};
...etc...
LIST
the return value is treated as a list of values:
my @x = foo();
my ($x) = foo();
() = foo(); # even though the results are discarded
print foo();
bar(foo()); # unless the bar subroutine has a prototype
print @hash{foo()}; # (hash slice)
...etc...
π¦ Lvalue subroutines π¦
when lvalue subroutines showed up in Perl 5.6, they invented a whole new type of contextual info, and it's independent of all the ones we just listed. iconique of them honestly. when an lvalue subroutine is called, it can either be called the ordinary way (so its result is treated as an ordinary value, aka an rvalue), or it can be called in a way where its result is considered updatable β an lvalue.
these kinda arcane terms (lvalue and rvalue) are so much easier to remember once you know why they're called that: think of a simple assignment statement left = right β the left-hand side is the lvalue, and the right-hand side is the rvalue. boom, unlocked π
so, and this is for lvalue subroutines only, there are two shiny new types of context:
RVALUE
the caller is definitely not trying to assign to the result:
foo();
my $x = foo();
...etc...
if the sub is declared without the ":lvalue" attribute, then it will always be in RVALUE context. periodt.
if you need to return values from an lvalue subroutine while in RVALUE context, you should use the "rreturn" function rather than an ordinary "return". otherwise you'll probably get a compile-time error in perl 5.6.1 and later π
LVALUE
either the caller is directly assigning to the result of the sub call:
foo() = $x;
foo() = (1, 1, 2, 3, 5, 8);
or the caller is making a reference to the result, which might get assigned to later:
my $ref = \(foo()); # Could now have: $$ref = 99;
# Note that this example imposes LIST context on the sub call.
# So we're taking a reference to the first element to be
# returned _in list context_.
# If we want to call the function in scalar context, we can
# do it like this:
my $ref = \(scalar foo());
or else the result of the function call is being used as part of the argument list for another function call:
bar(foo()); # Will *always* call foo in lvalue context,
# (provided that foo is an C<:lvalue> sub)
# regardless of what bar actually does.
the reason for that last case is that bar might be a sub which modifies its arguments. those are rare in contemporary Perl code, but perfectly possible:
sub bar {
$_[0] = 23;
}
(this is really a throwback to Perl 4, which didn't support explicit references. grandmacore π§)
π Assignment context π
the commonest use of lvalue subroutines is with the assignment statement:
size() = 12;
(list()) = (1..10);
a useful motto to remember when you're thinking about assignment statements is context comes from the left. check out code like this:
my ($x, $y, $z);
sub list () :lvalue { ($x, $y, $z) }
list = (1, 2, 3);
print "\$x = $x; \$y = $y; \$z = $z\n";
this prints "$x = ; $y = ; $z = 3", which may not be what you were expecting π the reason is that the assignment is in scalar context, so the comma operator is in scalar context too, and it discards all values but the last. you can fix it by writing "(list) = (1,2,3);" instead. slay.
if your lvalue subroutine is used on the left of an assignment statement, it's in ASSIGN context. if ASSIGN is the only argument to want(), then it returns a reference to an array of the value(s) of the right-hand side.
in this case, you should return with the "lnoreturn" function, rather than an ordinary "return".
this makes it super easy to write lvalue subroutines which do clever things:
use Want;
use strict;
sub backstr :lvalue {
if (want(qw'LVALUE ASSIGN')) {
my ($a) = want('ASSIGN');
$_[0] = reverse $a;
lnoreturn;
}
elsif (want('RVALUE')) {
rreturn scalar reverse $_[0];
}
else {
carp("Not in ASSIGN context");
}
return
}
print "foo -> ", backstr("foo"), "\n"; # foo -> oof
backstr(my $robin) = "nibor";
print "\$robin is now $robin\n"; # $robin is now robin
notice that you need to put a (meaningless) return statement at the end of the function, otherwise you will get the error Can't modify non-lvalue subroutine call in lvalue subroutine return. π not cute.
the only way to write that "backstr" function without using Want is to return a tied variable which is tied to a custom class. and like. that's a lot.
β Reference context β
sometimes in scalar context the caller is expecting a reference of some sort to be returned:
print foo()->(); # CODE reference expected
print foo()->{bar}; # HASH reference expected
print foo()->[23]; # ARRAY reference expected
print ${foo()}; # SCALAR reference expected
print foo()->bar(); # OBJECT reference expected
my $format = *{foo()}{FORMAT} # GLOB reference expected
you can check this using conditionals like "if (want('CODE'))". there's also a function wantref() which returns one of the strings "CODE", "HASH", "ARRAY", "GLOB", "SCALAR" or "OBJECT"; or the empty string if a reference is not expected. very demure, very mindful.
because want('SCALAR') is already taken (it selects ordinary scalar context), you have to use want('REFSCALAR') to find out if a SCALAR reference is expected. or you could use "want('REF') eq 'SCALAR'" of course, iykyk.
β οΈ be warned bestie:want('ARRAY')is a very different thing fromwantarray(). do not confuse them. do not.
π’ Item count π’
sometimes in list context the caller is expecting a particular number of items to be returned:
my ($x, $y) = foo(); # foo is expected to return two items
if you pass a number to the "want" function, then it will return true or false according to whether at least that many items are wanted. so if we're inside the definition of a sub which is being called as above, then:
want(1) returns true
want(2) returns true
want(3) returns false
sometimes there's no limit at all to the number of items that might be used:
my @x = foo();
do_something_with( foo() );
in this case, want(2), want(100), want(1E9) and so on will all return true; and so will want('Infinity'). infinite vibes truly π«
the "howmany" function can be used to find out how many items are wanted. if the context is scalar, then want(1) returns true and howmany() returns 1. if you want to check whether your result is being assigned to a singleton list, you can say "if (want('LIST', 1)) { ... }". chef's kiss.
π Boolean context π
sometimes the caller is only interested in the truth or falsity of a function's return value:
if (everything_is_okay()) {
# Carry on
}
print (foo() ? "ok\n" : "not ok\n");
in the following example, all subroutine calls are in BOOL context:
my $x = ( (foo() && !bar()) xor (baz() || quux()) );
boolean context, like the reference contexts up above, is considered to be a subcontext of SCALAR. it's the little sibling fr π
β¨ FUNCTIONS β¨
π want(SPECIFIERS)
Okay bestie, this is the main character of the whole module, the one you'll actually reach for 99% of the time. You hand it a list of context specifiers, and it hands you back true whenever every single one of those specifiers holds. All of them. No skipping. π
want('LVALUE', 'SCALAR'); # Are we in scalar lvalue context?
want('RVALUE', 3); # Are at least three rvalues wanted?
want('ARRAY'); # Is the return value used as an array ref?
And because sometimes the vibe is β¨rejectionβ¨, you can slap an exclamation mark in front of a specifier to say "nah, I need this one to be false":
want(2, '!3'); # Caller wants exactly two items.
want(qw'REF !CODE !GLOB'); # Expecting a reference that
# isn't a CODE or GLOB ref.
want(100, '!Infinity'); # Expecting at least 100 items,
# but there is a limit.
If REF is the only parameter you pass, then you get back the type of reference instead of a boolean. Lowkey this is just a synonym for the wantref function β it's here because it might come in handy if you don't wanna pollute your namespace by importing a whole bunch of functions, and also to vibe with Damian Conway's suggestion in RFC 21. π«Ά
And finally, the keyword COUNT is available, provided it's the only keyword you pass. Mixing COUNT with other keywords? That's an error, babes. This one is a synonym for the howmany function.
A full list of the permitted keywords is down in the ARGUMENTS section, keep scrolling. π
π rreturn
Use this one instead of return from inside an lvalue subroutine when you know you're in RVALUE context. If you try to use a normal old return, you'll get a compile-time error in Perl 5.6.1 and above unless you return an lvalue. π
(Note: this is no longer true in Perl 5.16, where an ordinary return will once again work. Growth. π±)
π« lnoreturn
Use this one instead of return from inside an lvalue subroutine when you're in ASSIGN context and you've used want('ASSIGN') to carry out the appropriate action. Iconic behaviour honestly. π
If you use rreturn or lnoreturn, then you have to put a bare return; at the very end of your lvalue subroutine, to stop the Perl compiler from complaining at you. Think of it as basically the same energy as the 1; you have to put at the end of a module. π
(Note: this is no longer true in Perl 5.16. We love an upgrade era. β¨)
π’ howmany()
Returns the expectation count, a.k.a. the number of items expected. If the expectation count is undefined, that means an unlimited number of items might be used (like when the return value is being assigned to an array). In void context the expectation count is zero, and in scalar context it's one.
Literally the same as want('COUNT'). β¨
π¦ wantref()
Returns the type of reference which the caller is expecting, or the empty string if the caller isn't expecting a reference right this second.
Same as want('REF'). Periodt. π
π EXAMPLES π
use Carp 'croak';
use Want 'howmany';
sub numbers {
my $count = howmany();
croak("Can't make an infinite list") if !defined($count);
return (1..$count);
}
my ($one, $two, $three) = numbers();
use Want 'want';
sub pi () {
if (want('ARRAY')) {
return [3, 1, 4, 1, 5, 9];
}
elsif (want('LIST')) {
return (3, 1, 4, 1, 5, 9);
}
else {
return 3;
}
}
print pi->[2]; # prints 4
print ((pi)[3]); # prints 1
π ARGUMENTS π
The permitted arguments to the want function are listed below, bestie. The list is structured so that sub-contexts appear beneath the context they're a part of β like a little family tree of vibes. π³
- VOID
- SCALAR
- REF
- REFSCALAR
- CODE
- HASH
- ARRAY
- GLOB
- OBJECT
- BOOL
- REF
- LIST
- COUNT
<number>- Infinity
- LVALUE
- ASSIGN
- RVALUE
π¦ EXPORT π¦
The want and rreturn functions are exported by default, no effort required, slay. The wantref and/or howmany functions can also be imported:
use Want qw'want howmany';
If you don't import these functions, you must qualify their names as (e.g.) Want::wantref. No shortcuts. π€
π§ INTERFACE π§
This module is still under development, and the public interface may change in future versions. But the want function can now be regarded as stable. π
I'd be interested to know how you're using this module. fr fr, tell me. π«Ά
π€ SUBTLETIES π€
There are two different levels of BOOL context, and this is the part where it gets spicy. πΆοΈ
Pure boolean context happens in conditional expressions, and in the operands of the xor and !/not operators. Pure boolean context also propagates down through the && and || operators.
However β consider an expression like my $x = foo() && "yes". The subroutine here is called in pseudo-boolean context β its return value isn't entirely ignored, because the undefined value, the empty string and the integer 0 are all false. So it still kinda matters. π
At the moment want('BOOL') is true in either pure or pseudo boolean context. Let me know if this is a problem. π
π BUGS π
- Doesn't work from inside a tie-handler. That's it, that's the bug. π
π AUTHOR π
Robin Houston, <robin@cpan.org>
Thanks to Damian Conway for encouragement and good suggestions, and Father Chrysostomos for a patch. Genuinely so lovely. π«Άβ¨
π SEE ALSO π
"wantarray"in perlfunc- Perl6 RFC 21, by Damian Conway.
http://dev.perl.org/rfc/21.html
Β©οΈ COPYRIGHT Β©οΈ
Copyright (c) 2001-2012, Robin Houston. All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Perl itself.
and that's a wrap on this lil manpage, bestie π this was perl v5.42.3, dated 2026-08-19, and that's Want(3pm) β go forth and know thy context, iykyk β¨ππ
π¦ where this page comes from
- ubuntu stonking: libwant-perl 0.29-2build6 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms