Chris,
You can examining the return value from a function by examining it's
'context'. List context is indicated by a true return value. If it returns a
value that is false but defined, then the function's return value will be
used in scalar context. If it returns undef, it isn't being asked to provide
a value at all.
if (myFunction()) {
print "In list context\n";
return @many_things;
} elsif (defined myFunction()) {
print "In scalar context\n";
return $one_thing;
} else {
print "In void context\n";
return; # nothing
}
mysub(); # void context
$a = mysub(); # scalar context
if (mysub()) { } # scalar context
@a = mysub(); # list context
print mysub(); # list context
Regards,
Piers
-----Original Message-----
From: Chris Ralph [mailto:webmaster@g...]
Sent: 17 November 2002 04:57
To: Pro_Perl
Subject: [pro_perl] Determine context
Hi,
Does anyone know how to tell if a return value from a function should be
scalar or other context ?
Example:
sub foobar
{
# Code here
if ( scalar_was_requested ){
return $scalar;
}elsif ( array_was_requested){
return @array;
}else{
return "error";
}
}
Now I call the function, and either an array or scalar should be returned,
depending on the context:
$val = foobar; # return scalar
@vals = foobar; # return array
What I can't work out is how to tell which variable type was requested..
I know a lot of built-in functions do this, but how do I go about
producing this behaviour in user defined functions ?
Chris