CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate: wantarray returns 1 when function called in void context: Edit Log



rpaskudniak
User


Jul 28, 2013, 5:08 PM


Views: 5018
wantarray returns 1 when function called in void context

Hi Family.

I was trying to be oh so elegant!

I wrote a subroutine to be callable either passing a floating point number or a reference to an array of such. (I specifically die if caller passes a list.) It can return a scalar if called in a scalar context, or a transform of the original array if called in a list context and passed that reference. What if I want to operate on the passed array itself? Then I call it in a void context, like the way we call chomp.

My function looks something like this:

Code
sub realify 
{
my $thing = $_[0]; # Don't shift, we might need to modify in place
my $rval = 0.0;

die "You may not pass a list to realify(); use array reference"
if ($#_ > 0);
# Real or complex, if absolute value is really tiny, "correct" to 0
#
if (wantarray) # Array context: Assume $thing is an
{ # array reference.
my @rlist = <some stuff based on @$thing>; # Return list
return @rlist;
}
elsif (defined(wantarray)) # Scalar context: assume $thing is a scalar
{ # and caller wants a new value returned
$rval = <Some stuff to set up a scalar return value>
return $rval;
}
else # Void context: Operate on the passed object.
{
<Some stuff to operate directly on $_[0] or the array it references>

# Note: No return statement - void context, after all.
}
}

I have called it with something like the following line:

Code
realify($some_scalar)

So wantarray should be undefined! But NooOOOooo! It returns a 1! Mad This forces my code into logic for which it was not intended. So the bottom line for this post is:
Why is wantarray returning a 1 when I clearly had called the function in void context? It should be undefined.

My workaround it not to be so blessed clever and always return something, even in void context but then I don't learn the correct solution to operating in place or not. (In fact, the earlier, working, version was scalar parameter with scalar context only; I was using the map {} command to operate on the whole array.)

Thanks much for guidance.
--------------------
-- Rasputin Paskudniak (In perpetual pursuit of undomesticated, semi-aquatic avians)


(This post was edited by rpaskudniak on Jul 28, 2013, 7:42 PM)


Edit Log:
Post edited by rpaskudniak (User) on Jul 28, 2013, 7:40 PM
Post edited by rpaskudniak (User) on Jul 28, 2013, 7:42 PM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives