Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

context-sensitivity for selfwritten functions

by tos (Deacon)
on Jan 28, 2004 at 09:03 UTC ( #324624=perlquestion: print w/replies, xml ) Need Help??

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

Dear Monks,

some intrinsic functions as f.i. 'localtime' are contextsensitive.

How can i realize this behavior with my own functions ? How does my function know whether it has to return a scalar- or a list-value ? Is there something to do with overloading ?

thanks in advance and regards, tos

  • Comment on context-sensitivity for selfwritten functions

Replies are listed 'Best First'.
Re: context-sensitivity for selfwritten functions
by Abigail-II (Bishop) on Jan 28, 2004 at 09:32 UTC
    #!/usr/bin/perl use strict; use warnings; sub func { my $context = wantarray; print "VOID" if not defined $context; return "SCALAR" if defined $context && !$context; return "LIST" if $context; } print "Context is: "; func (); print "\n"; print "Context is: ". func (); print "\n"; print "Context is: ", func (); print "\n"; __END__ Context is: VOID Context is: SCALAR Context is: LIST

    Abigail

Re: context-sensitivity for selfwritten functions
by rob_au (Abbot) on Jan 28, 2004 at 09:06 UTC
    In order to distinguish between scalar and list return contexts, take a look at the wantarray function - See perldoc -f wantarray).

    This functionality has been expanded further in the Want module which provides a greater generalisation of return contexts including top level contexts such as void, scalar and list, lvalue subroutine context and referential contexts (such as scalar, hash, array, object and alike).

     

    perl -le "print unpack'N', pack'B32', '00000000000000000000001010111000'"

Re: context-sensitivity for selfwritten functions
by l3nz (Friar) on Jan 28, 2004 at 09:29 UTC
    An excellent example of context sensitivity is given in this trim() magic function example by our fellow saint japhy.

    I think it shows all you need to build a context-sensitive function: the key, as you can see, is a defined wantarray.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://324624]
Approved by b10m
Front-paged by broquaint
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (7)
As of 2021-03-02 10:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favorite kind of desktop background is:











    Results (42 votes). Check out past polls.

    Notices?