http://qs321.pair.com?node_id=324624

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.