Subroutine, scalar vs. list context. Define a subroutine that takes the radius o
ID: 3631367 • Letter: S
Question
Subroutine, scalar vs. list context. Define a subroutine that takes the radius of a circle as input, it returns the area of the circle if it is called in a scalar context: or a list that contains the area, the diameter and the circumference if called in a list context. Demonstrate the subroutine's usage with a small calling program. Hint: the formulas are ( r is the radius ) : area = pi r2, diameter = 2r, circumference = 2pi r. You may define a constant pi with value 3.141593. Hint: use the want array ( ) function.Explanation / Answer
Please rate - thanks
As always, do let me know if you have any question; I'll rush over a fix.
sub isIT {
my $pi = 3.141593;
return(wantarray() ? ($pi*$_[0]*$_[0], 2.*$_[0], 2.*$pi*$_[0]) : $pi*$_[0]*$_[0]);
}
my $r = 10;
$result = &isIT($r);
print "area= $result", " ";
@result = &isIT($r);
print "area= @result[0] diameter= @result[1] circumference= @result[2] ";
Here are the results:
area= 314.1593
area= 314.1593 diameter= 20 circumference= 62.83186