Adding two numbers in Perl using subroutine

Here, we are going to learn how to add two numbers in Perl using subroutine?
Submitted by Godwill Tetah, on December 02, 2020

Here, we will write a program which takes two values (integers) and calculates the sum.

Program/Source Code:

File name: index.pl

#Perl addition subroutine

sub add {
    $x = $_[0];
    $y = $_[1];
    $z = $x + $y;
    print "Answer: $z ";
}
print "input first number \n";

$num1 = <STDIN>;

print "input second number \n";

$num2 = <STDIN>;

add( $num1, $num2 );

Output:

input first number
10
input second number
20
Answer: 30

Explanation:

  • So from the code above, the name of our subroutine is add.
  • In the body of the subroutine, we have three variables, $x, $y, $z. where the variable $z contains the addition of the other two variables.
  • The symbols $_ assigned to variables $x and $y simply refers to a shift of a parameter to a variable. In Perl, the list of parameters passed when the subroutine is called can be accessed using the numbering/index system of an array where the first element has the number zero (0).
  • That is the reason why $_[0] means the first parameter will be assigned to variable $x and so on.
  • Remember we are to get the numbers to be added from the user and not assigning a number directly in our source code. That's why the command <STDIN> is assigned to the variable $num1, as it gets prompts the user to input data.
  • The same things is done for variable $num2.
  • The subroutine is then called and the variables which store user input are then passed as parameters.
  • \t and \n stand for space and new line respectively.


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.