Perl通过参数传递将标量传递给子程序

时间:2016-03-30 08:36:10

标签: perl

如何通过参数传递将标量传递给子程序?我编写了以下代码,希望将$radiussub get_radius传递给sub area_circle

#!/usr/bin/env perl

use warnings;
use strict;
use Math::Trig ':pi';


sub get_radius {
     print "Enter the radius of the circle: \n";
     my $radius = <STDIN>;

}

sub area_circle {
     my $radius = get_radius();
     my $area = 0;
     $area = pi * ($radius **2);
     return $area;
}

my $area = area_circle;
print "The area is: $area \n";

2 个答案:

答案 0 :(得分:0)

您可以使用以下任何一种方法......

#!/usr/bin/env perl
use warnings;
use strict;
use Math::Trig ':pi';

my $radius = 0;  #####
sub get_radius {
     print "Enter the radius of the circle: \n";
     $radius = <STDIN>;
}

sub area_circle {
     get_radius();  #####
     my $area = 0;
     $area = pi * ($radius **2);
     return $area;
}

my $area = area_circle;
print "The area is: $area \n";

OR

#!/usr/bin/env perl
use warnings;
use strict;
use Math::Trig ':pi';

sub get_radius {
     print "Enter the radius of the circle: \n";
     my $radius = <STDIN>;
     return $radius
}

sub area_circle {
     my $radius = get_radius();
     my $area = 0;
     $area = pi * ($radius **2);
     return $area;
}

my $area = area_circle;
print "The area is: $area \n";

答案 1 :(得分:0)

subs从@_数组中获取它们的参数,如下所示:

sub whatever {
    my ($param1, $param2) = @_;
}

sub whatever {
    my $param1 = $_[0];
    my $param2 = $_[1];
}

在您的代码中:

#!/usr/bin/env perl

use warnings;
use strict;
use Math::Trig ':pi';

sub get_radius {
    print "Enter the radius of the circle: \n";
    my $radius = <STDIN>;
    return $radius; 
}

sub area_circle {
    my ($radius) = @_;

    my $area = 0;
    $area = pi * ($radius **2);
    return $area;
}

my $radius = get_radius;
my $area = area_circle( $radius );
print "The area is: $area \n";

注意半径现在是如何传递到area_circle的,因此area_circle现在不再绑定到get_radius子,现在可以计算圆的面积,无论从哪里获取半径。