{
    "mode": "perldoc",
    "parameter": "Want",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Want/json",
    "generated": "2026-06-12T06:20:35Z",
    "synopsis": "use Want;\nsub foo :lvalue {\nif    (want(qw'LVALUE ASSIGN')) {\nprint \"We have been assigned \", want('ASSIGN');\nlnoreturn;\n}\nelsif (want('LIST')) {\nrreturn (1, 2, 3);\n}\nelsif (want('BOOL')) {\nrreturn 0;\n}\nelsif (want(qw'SCALAR !REF')) {\nrreturn 23;\n}\nelsif (want('HASH')) {\nrreturn { foo => 17, bar => 23 };\n}\nreturn;  # You have to put this at the end to keep the compiler happy\n}",
    "sections": {
        "NAME": {
            "content": "Want - A generalisation of \"wantarray\"\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use Want;\nsub foo :lvalue {\nif    (want(qw'LVALUE ASSIGN')) {\nprint \"We have been assigned \", want('ASSIGN');\nlnoreturn;\n}\nelsif (want('LIST')) {\nrreturn (1, 2, 3);\n}\nelsif (want('BOOL')) {\nrreturn 0;\n}\nelsif (want(qw'SCALAR !REF')) {\nrreturn 23;\n}\nelsif (want('HASH')) {\nrreturn { foo => 17, bar => 23 };\n}\nreturn;  # You have to put this at the end to keep the compiler happy\n}\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This module generalises the mechanism of the wantarray function, allowing a function to\ndetermine in some detail how its return value is going to be immediately used.\n",
            "subsections": [
                {
                    "name": "Top-level contexts:",
                    "content": "The three kinds of top-level context are well known:\n\nVOID\nThe return value is not being used in any way. It could be an entire statement like\n\"foo();\", or the last component of a compound statement which is itself in void context,\nsuch as \"$test || foo();\"n. Be warned that the last statement of a subroutine will be in\nwhatever context the subroutine was called in, because the result is implicitly returned.\n\nSCALAR\nThe return value is being treated as a scalar value of some sort:\n\nmy $x = foo();\n$y += foo();\nprint \"123\" x foo();\nprint scalar foo();\nwarn foo()->{23};\n...etc...\n\nLIST\nThe return value is treated as a list of values:\n\nmy @x = foo();\nmy ($x) = foo();\n() = foo();           # even though the results are discarded\nprint foo();\nbar(foo());           # unless the bar subroutine has a prototype\nprint @hash{foo()};   # (hash slice)\n...etc...\n"
                },
                {
                    "name": "Lvalue subroutines:",
                    "content": "The introduction of lvalue subroutines in Perl 5.6 has created a new type of contextual\ninformation, which is independent of those listed above. When an lvalue subroutine is called, it\ncan either be called in the ordinary way (so that its result is treated as an ordinary value, an\nrvalue); or else it can be called so that its result is considered updatable, an lvalue.\n\nThese rather arcane terms (lvalue and rvalue) are easier to remember if you know why they are so\ncalled. If you consider a simple assignment statement \"left = right\", then the left-hand side is\nan lvalue and the right-hand side is an rvalue.\n\nSo (for lvalue subroutines only) there are two new types of context:\n\nRVALUE\nThe caller is definitely not trying to assign to the result:\n\nfoo();\nmy $x = foo();\n...etc...\n\nIf the sub is declared without the \":lvalue\" attribute, then it will *always* be in RVALUE\ncontext.\n\nIf you need to return values from an lvalue subroutine in RVALUE context, you should use the\n\"rreturn\" function rather than an ordinary \"return\". Otherwise you'll probably get a\ncompile-time error in perl 5.6.1 and later.\n\nLVALUE\nEither the caller is directly assigning to the result of the sub call:\n\nfoo() = $x;\nfoo() = (1, 1, 2, 3, 5, 8);\n\nor the caller is making a reference to the result, which might be assigned to later:\n\nmy $ref = \\(foo());   # Could now have: $$ref = 99;\n\n# Note that this example imposes LIST context on the sub call.\n# So we're taking a reference to the first element to be\n# returned in list context.\n# If we want to call the function in scalar context, we can\n# do it like this:\nmy $ref = \\(scalar foo());\n\nor else the result of the function call is being used as part of the argument list for\n*another* function call:\n\nbar(foo());   # Will *always* call foo in lvalue context,\n# (provided that foo is an C<:lvalue> sub)\n# regardless of what bar actually does.\n\nThe reason for this last case is that bar might be a sub which modifies its arguments.\nThey're rare in contemporary Perl code, but perfectly possible:\n\nsub bar {\n$[0] = 23;\n}\n\n(This is really a throwback to Perl 4, which didn't support explicit references.)\n"
                },
                {
                    "name": "Assignment context:",
                    "content": "The commonest use of lvalue subroutines is with the assignment statement:\n\nsize() = 12;\n(list()) = (1..10);\n\nA useful motto to remember when thinking about assignment statements is *context comes from the\nleft*. Consider code like this:\n\nmy ($x, $y, $z);\nsub list () :lvalue { ($x, $y, $z) }\nlist = (1, 2, 3);\nprint \"\\$x = $x; \\$y = $y; \\$z = $z\\n\";\n\nThis prints \"$x = ; $y = ; $z = 3\", which may not be what you were expecting. The reason is that\nthe assignment is in scalar context, so the comma operator is in scalar context too, and\ndiscards all values but the last. You can fix it by writing \"(list) = (1,2,3);\" instead.\n\nIf your lvalue subroutine is used on the left of an assignment statement, it's in ASSIGN\ncontext. If ASSIGN is the only argument to \"want()\", then it returns a reference to an array of\nthe value(s) of the right-hand side.\n\nIn this case, you should return with the \"lnoreturn\" function, rather than an ordinary \"return\".\n\nThis makes it very easy to write lvalue subroutines which do clever things:\n\nuse Want;\nuse strict;\nsub backstr :lvalue {\nif (want(qw'LVALUE ASSIGN')) {\nmy ($a) = want('ASSIGN');\n$[0] = reverse $a;\nlnoreturn;\n}\nelsif (want('RVALUE')) {\nrreturn scalar reverse $[0];\n}\nelse {\ncarp(\"Not in ASSIGN context\");\n}\nreturn\n}\n\nprint \"foo -> \", backstr(\"foo\"), \"\\n\";        # foo -> oof\nbackstr(my $robin) = \"nibor\";\nprint \"\\$robin is now $robin\\n\";              # $robin is now robin\n\nNotice that you need to put a (meaningless) return statement at the end of the function,\notherwise you will get the error *Can't modify non-lvalue subroutine call in lvalue subroutine\nreturn*.\n\nThe only way to write that \"backstr\" function without using Want is to return a tied variable\nwhich is tied to a custom class.\n"
                },
                {
                    "name": "Reference context:",
                    "content": "Sometimes in scalar context the caller is expecting a reference of some sort to be returned:\n\nprint foo()->();     # CODE reference expected\nprint foo()->{bar};  # HASH reference expected\nprint foo()->[23];   # ARRAY reference expected\nprint ${foo()};      # SCALAR reference expected\nprint foo()->bar();  # OBJECT reference expected\n\nmy $format = *{foo()}{FORMAT} # GLOB reference expected\n\nYou can check this using conditionals like \"if (want('CODE'))\". There is also a function\n\"wantref()\" which returns one of the strings \"CODE\", \"HASH\", \"ARRAY\", \"GLOB\", \"SCALAR\" or\n\"OBJECT\"; or the empty string if a reference is not expected.\n\nBecause \"want('SCALAR')\" is already used to select ordinary scalar context, you have to use\n\"want('REFSCALAR')\" to find out if a SCALAR reference is expected. Or you could use \"want('REF')\neq 'SCALAR'\" of course.\n\nBe warned that \"want('ARRAY')\" is a very different thing from \"wantarray()\".\n"
                },
                {
                    "name": "Item count",
                    "content": "Sometimes in list context the caller is expecting a particular number of items to be returned:\n\nmy ($x, $y) = foo();   # foo is expected to return two items\n\nIf you pass a number to the \"want\" function, then it will return true or false according to\nwhether at least that many items are wanted. So if we are in the definition of a sub which is\nbeing called as above, then:\n\nwant(1) returns true\nwant(2) returns true\nwant(3) returns false\n\nSometimes there is no limit to the number of items that might be used:\n\nmy @x = foo();\ndosomethingwith( foo() );\n\nIn this case, want(2), \"want(100)\", \"want(1E9)\" and so on will all return true; and so will\n\"want('Infinity')\".\n\nThe \"howmany\" function can be used to find out how many items are wanted. If the context is\nscalar, then want(1) returns true and \"howmany()\" returns 1. If you want to check whether your\nresult is being assigned to a singleton list, you can say \"if (want('LIST', 1)) { ... }\".\n"
                },
                {
                    "name": "Boolean context",
                    "content": "Sometimes the caller is only interested in the truth or falsity of a function's return value:\n\nif (everythingisokay()) {\n# Carry on\n}\n\nprint (foo() ? \"ok\\n\" : \"not ok\\n\");\n\nIn the following example, all subroutine calls are in BOOL context:\n\nmy $x = ( (foo() && !bar()) xor (baz() || quux()) );\n\nBoolean context, like the reference contexts above, is considered to be a subcontext of SCALAR.\n"
                }
            ]
        },
        "FUNCTIONS": {
            "content": "",
            "subsections": [
                {
                    "name": "want",
                    "content": "This is the primary interface to this module, and should suffice for most purposes. You pass\nit a list of context specifiers, and the return value is true whenever all of the specifiers\nhold.\n\nwant('LVALUE', 'SCALAR');   # Are we in scalar lvalue context?\nwant('RVALUE', 3);          # Are at least three rvalues wanted?\nwant('ARRAY');      # Is the return value used as an array ref?\n\nYou can also prefix a specifier with an exclamation mark to indicate that you don't want it\nto be true\n\nwant(2, '!3');              # Caller wants exactly two items.\nwant(qw'REF !CODE !GLOB');  # Expecting a reference that\n#   isn't a CODE or GLOB ref.\nwant(100, '!Infinity');     # Expecting at least 100 items,\n#   but there is a limit.\n\nIf the *REF* keyword is the only parameter passed, then the type of reference will be\nreturned. This is just a synonym for the \"wantref\" function: it's included because you might\nfind it useful if you don't want to pollute your namespace by importing several functions,\nand to conform to Damian Conway's suggestion in RFC 21.\n\nFinally, the keyword *COUNT* can be used, provided that it's the only keyword you pass.\nMixing COUNT with other keywords is an error. This is a synonym for the \"howmany\" function.\n\nA full list of the permitted keyword is in the ARGUMENTS section below.\n\nrreturn\nUse this function instead of \"return\" from inside an lvalue subroutine when you know that\nyou're in RVALUE context. If you try to use a normal \"return\", you'll get a compile-time\nerror in Perl 5.6.1 and above unless you return an lvalue. (Note: this is no longer true in\nPerl 5.16, where an ordinary return will once again work.)\n\nlnoreturn\nUse this function instead of \"return\" from inside an lvalue subroutine when you're in ASSIGN\ncontext and you've used \"want('ASSIGN')\" to carry out the appropriate action.\n\nIf you use \"rreturn\" or \"lnoreturn\", then you have to put a bare \"return;\" at the very end\nof your lvalue subroutine, in order to stop the Perl compiler from complaining. Think of it\nas akin to the \"1;\" that you have to put at the end of a module. (Note: this is no longer\ntrue in Perl 5.16.)\n"
                },
                {
                    "name": "howmany",
                    "content": "Returns the *expectation count*, i.e. the number of items expected. If the expectation count\nis undefined, that indicates that an unlimited number of items might be used (e.g. the\nreturn value is being assigned to an array). In void context the expectation count is zero,\nand in scalar context it is one.\n\nThe same as \"want('COUNT')\".\n"
                },
                {
                    "name": "wantref",
                    "content": "Returns the type of reference which the caller is expecting, or the empty string if the\ncaller isn't expecting a reference immediately.\n\nThe same as \"want('REF')\".\n"
                }
            ]
        },
        "EXAMPLES": {
            "content": "use Carp 'croak';\nuse Want 'howmany';\nsub numbers {\nmy $count = howmany();\ncroak(\"Can't make an infinite list\") if !defined($count);\nreturn (1..$count);\n}\nmy ($one, $two, $three) = numbers();\n\n\nuse Want 'want';\nsub pi () {\nif    (want('ARRAY')) {\nreturn [3, 1, 4, 1, 5, 9];\n}\nelsif (want('LIST')) {\nreturn (3, 1, 4, 1, 5, 9);\n}\nelse {\nreturn 3;\n}\n}\nprint pi->[2];      # prints 4\nprint ((pi)[3]);    # prints 1\n",
            "subsections": []
        },
        "ARGUMENTS": {
            "content": "The permitted arguments to the \"want\" function are listed below. The list is structured so that\nsub-contexts appear below the context that they are part of.\n\n*   VOID\n\n*   SCALAR\n\n*   REF\n\n*   REFSCALAR\n\n*   CODE\n\n*   HASH\n\n*   ARRAY\n\n*   GLOB\n\n*   OBJECT\n\n*   BOOL\n\n*   LIST\n\n*   COUNT\n\n*   <number>\n\n*   Infinity\n\n*   LVALUE\n\n*   ASSIGN\n\n*   RVALUE\n",
            "subsections": []
        },
        "EXPORT": {
            "content": "The \"want\" and \"rreturn\" functions are exported by default. The \"wantref\" and/or \"howmany\"\nfunctions can also be imported:\n\nuse Want qw'want howmany';\n\nIf you don't import these functions, you must qualify their names as (e.g.) \"Want::wantref\".\n",
            "subsections": []
        },
        "INTERFACE": {
            "content": "This module is still under development, and the public interface may change in future versions.\nThe \"want\" function can now be regarded as stable.\n\nI'd be interested to know how you're using this module.\n",
            "subsections": []
        },
        "SUBTLETIES": {
            "content": "There are two different levels of BOOL context. *Pure* boolean context occurs in conditional\nexpressions, and the operands of the \"xor\" and \"!\"/\"not\" operators. Pure boolean context also\npropagates down through the \"&&\" and \"||\" operators.\n\nHowever, consider an expression like \"my $x = foo() && \"yes\"\". The subroutine is called in\n*pseudo*-boolean context - its return value isn't entirely ignored, because the undefined value,\nthe empty string and the integer 0 are all false.\n\nAt the moment \"want('BOOL')\" is true in either pure or pseudo boolean context. Let me know if\nthis is a problem.\n",
            "subsections": []
        },
        "BUGS": {
            "content": "* Doesn't work from inside a tie-handler.\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Robin Houston, <robin@cpan.org>\n\nThanks to Damian Conway for encouragement and good suggestions, and Father Chrysostomos for a\npatch.\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "*   \"wantarray\" in perlfunc\n\n*   Perl6 RFC 21, by Damian Conway. http://dev.perl.org/rfc/21.html\n",
            "subsections": []
        },
        "COPYRIGHT": {
            "content": "Copyright (c) 2001-2012, Robin Houston. All Rights Reserved. This module is free software. It\nmay be used, redistributed and/or modified under the same terms as Perl itself.\n",
            "subsections": []
        }
    },
    "summary": "Want - A generalisation of \"wantarray\"",
    "flags": [],
    "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"
    ],
    "see_also": []
}