R
Ronald Fischer
Does someone have an elegant solution to the following problem?
Consider a function F which is supposed to do the following:
(1) Perform X()
(2) Perform Y(); Y returns a different result in array- or
scalar context. The result of Y should be returned as the
result of F (which hence is also sensitive to array- vs.
scalar context)
(3) Perform Z() (which may do some cleanup-work, which can be
done only after Y has been executed).
Under these premises, what is an elegant way to code F? Here is
one straightforward, but not-so-elegant solution:
sub F()
{
X();
if(wantarray)
{ my @result=Y(); Z(); @result }
else
{ my $result=Y(); Z(); $result }
}
This works, and might be acceptable in this simple case, but
it is a bit awkward, because Z() has be repeated in both
branches, and there are two exit points instead of one.
Maybe someone can improve on this?
Ronald
Consider a function F which is supposed to do the following:
(1) Perform X()
(2) Perform Y(); Y returns a different result in array- or
scalar context. The result of Y should be returned as the
result of F (which hence is also sensitive to array- vs.
scalar context)
(3) Perform Z() (which may do some cleanup-work, which can be
done only after Y has been executed).
Under these premises, what is an elegant way to code F? Here is
one straightforward, but not-so-elegant solution:
sub F()
{
X();
if(wantarray)
{ my @result=Y(); Z(); @result }
else
{ my $result=Y(); Z(); $result }
}
This works, and might be acceptable in this simple case, but
it is a bit awkward, because Z() has be repeated in both
branches, and there are two exit points instead of one.
Maybe someone can improve on this?
Ronald