On Thu, Sep 05, 2002 at 07:16:45PM -0400, Wiggins d'Anconia wrote:
> if ( 1 > my_sub_that_returns ) {
>       # do something cool.....
> }

> It seems like this case could go either way, that is, in some cases your 
> function could simply be returning a scalar value, say 0 for a failure 
> in the sub or something, or it could be returning a list (array) that 
> you are then wanting to check the length of to determine if you want to 
> "do something cool..." which I realize is just a scalar in array's 
> clothing,

A list and array are two different things.  In scalar context, a list
evaluates to the last element of the list, an array evaluates to a count of
the elements.  Not entirely germane to the discussion, but you said "list
(array)" as if they were the same thing, and evaluated to the same thing in
scalar context.


> however, can the wantarray know this before it returns?

Can you?  Given your code, how do you determine if the user wanted a count
of the number of elements, or simply a true or false value indicating the
subroutine's success?  Granted, the comparison is a little odd for a simple
test for success, but you're still asking the code to determine the intent
of the programmer.

Or are you perhaps asking if wantarray can distinguish between a scalar and
a boolean context?  Unfortunately, it can't.  However, you can get quite a
few of the context-specific behaviours you're asking about by returning an
overload object.  So you could, conceivably, return an object that evaluated
one way in boolean context, another when used as a string or number, and
another when compared to a number:

    {
        package Foo;
        use overload
            bool    =>  sub {  0 },
            q{""}   =>  sub { 42 },
            "0+"    =>  sub { 24 },
        ;
    }

    sub my_sub { return bless({}, "Foo") }


    unless (my_sub()) {
        print "my_sub() returned false!\n";
    }

    print scalar my_sub(), "\n";


would print

    my_sub() returned false!
    1

(I omitted dealing with numeric comparisons; it's a little more complex, but
still doable.)

This isn't perfect, as you have to use the return value as a string or
number to get it to evaluated differently, but it's close.  I wouldn't
suggest this approach; as is true of most uses of overloading, it can be
terribly confusing when actually applied.


Michael
--
Administrator                      www.shoebox.net
Programmer, System Administrator   www.gallanttech.com
--

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to