Home: Fun With Perl: Perl Quizzes - Learn Perl the Fun Way:
Return



Cure
User

Jul 18, 2000, 8:44 AM


Views: 21541
Return

Are the 2 subroutines equivalent? Explain your answer.

sub new {
return
}

sub new {
return wantarray ? () : undef
}

Cure


mckhendry
Deleted

Jul 18, 2000, 9:28 AM


Views: 21541
Re: Return

If your question is what is the difference in what is returned, then the answer is the first subroutine returns nothing and the second returns undef.

If your question is what is the difference in performance, well then obviously the subroutine that uses wantarray will take slightly longer. That is because the ternary operator must be evaluated in conjunction with wantarray where as the first subroutine just returns to where it was called from.

As for what the second second subroutine does:

wantarray returns true if the context of the currently executing subroutine is looking for a list value. It returns false if it is looking for a scalar. My guess is since return is looking for a scalar (in this context) that undef is returned instead of the empty list.


japhy
Enthusiast

Jul 18, 2000, 3:48 PM


Views: 21541
Re: Return

mckhendry - there's no indication as to the context of these two subroutines. As they stand, they are equivalent. return returns the empty list in list context, and undef in scalar context. In fact, the output of the deparser shows that return() and return () are really return +() -- that is, explicitly returning an empty list.

return on its own is really return wantarray ? () : undef.


Cure
User

Jul 25, 2000, 8:48 AM


Views: 21541
Re: Return

sub new {return}

sub new {return wantarray ? () : undef}

Are the 2 subroutines equivalent and the ANSWER IS YES.


return with NO ARGUMENTS is really return wantarray ? () : undef.


GOOD job japhy.


Cure