简体   繁体   中英

Perl transfer scalar to subroutine by parameter passing

How do I transfer a scalar to a subroutine by parameter passing? I have written the following code and want to pass the $radius from sub get_radius to 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";

You can use any of the following methods...

#!/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";

subs take their parameters from the @_ array, like this:

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

or

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

In the context of your code:

#!/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";

Note how the radius is now being passed in to area_circle, so that area_circle is now no longer tied to the get_radius sub and can now calculate the area of a circle no matter where the radius is fetched from.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM