Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

help needed in wantarray

by uva (Sexton)
on Feb 10, 2006 at 12:37 UTC ( [id://529343]=perlquestion: print w/replies, xml ) Need Help??

uva has asked for the wisdom of the Perl Monks concerning the following question:

how the execution of the program decides wantarray function returns true or false.i tried in the coding but it always returned ture .i read the documentation also, in that they said about the context,i could not understand.can you please give example(code) which explains that.

Replies are listed 'Best First'.
Re: help needed in wantarray
by xdg (Monsignor) on Feb 10, 2006 at 12:46 UTC

    The "context" means the context that the function is called in -- whether the values of the function will be used in list or scalar context.

    use strict; use warnings; sub what_do_you_want { print wantarray ? "list\n" : "scalar\n"; } my @list = what_do_you_want(); # prints "list" my $scalar = what_do_you_want() # prints "scalar"

    -xdg

    Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Re: help needed in wantarray
by dorward (Curate) on Feb 10, 2006 at 12:43 UTC
    use strict; use warnings; sub foo { if (wantarray()) { print "Want!\n"; } else { print "Don't want!\n"; } } my $bar = foo(); my @baz = foo();
Re: help needed in wantarray
by brian_d_foy (Abbot) on Feb 10, 2006 at 18:26 UTC

    Actually, wantarray has three distinct return values: true, false but defined, and undef. These correspond to list context, scalar context, and void context.

    sub fred { ... unless( defined wantarray ) { ...void context } elsif( wantarray ) { ...list context } else { ...scalar context } }

    You then ensure you're calling fred in the right context.

    fred(); # void my $fred = fred(); # scalar my( $fred ) = fred(); # list (because of the parens) my @fred = fred; # list print fred(); # list, print is a list operator print scalar fred(); # scalar

    For instance, you might look at Hook::LexWrap (or my TPJ article on it: "Wrapping Subroutines to Trace Code Execution".

    --
    brian d foy <brian@stonehenge.com>
    Subscribe to The Perl Review

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://529343]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (2)
As of 2025-01-13 14:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which URL do you most often use to access this site?












    Results (32 votes). Check out past polls.