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

hi. i'm trying to write context-sensitive subroutines using wantarray (or maybe Want). however when i call a subroutine from printf it fails like in sub t {return wantarray} printf "returns %i\n", t() ##returns 1 printf "returns %i\n", scalar t() ##returns 0 isn't there a way to pass the info of how many arguments printf expects to the subroutine without the explicit scalar? i hope my question is understandable, thanks for any help tim

Replies are listed 'Best First'.
Re: context of printf ->wantarray
by moritz (Cardinal) on Nov 05, 2010 at 13:03 UTC
    It's not wantarray() that fails, but an intrinsic problem in your approach:

    The arguments of a function are evaluated before the function is called. So in the case of printf $format, subroutine() the call to subroutine() is carried out before printf even had a chance to examine the $format argument. So even if it had a mechanism for signalling how many more arguments it needs, it would be too late for that. Instead it just always takes a list of arguments.

    So I suggest you try to find a different design that isn't based so heavily on introspection.

    Perl 6 - links to (nearly) everything that is Perl 6.
Re: context of printf ->wantarray
by Fletch (Bishop) on Nov 05, 2010 at 13:28 UTC

    Other advice aside you might check out Contextual::Return and make sure you're not reinventing wheels if you're determined to take this route.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: context of printf ->wantarray
by kcott (Archbishop) on Nov 05, 2010 at 13:00 UTC

    I think you're maybe working from a false premise there. printf does want an array, so when you call t() in that context it returns TRUE (i.e. 1). When you specify scalar, it doesn't want an array and returns FALSE (i.e. 0).

    Take a look at the documentation for wantarray.

    -- Ken