perl function my

h‮ww//:sptt‬w.theitroad.com

The my keyword in Perl is used to declare a new lexical variable. It restricts the scope of the variable to the current block, including any nested blocks, and makes it invisible outside of that scope. Here's an example:

sub add_numbers {
  my $x = shift;
  my $y = shift;
  my $result = $x + $y;
  return $result;
}

# main program
my $a = 2;
my $b = 3;
my $sum = add_numbers($a, $b);

print "The sum of $a and $b is $sum\n";

In this example, we define a subroutine called add_numbers that takes two arguments, $x and $y. Within the subroutine, we use the my keyword to declare a new variable called $result, which is the sum of $x and $y.

In the main program, we declare two more variables using the my keyword: $a and $b. We then call the add_numbers subroutine with these two variables as arguments and store the result in another variable called $sum.

Finally, we use the print function to display the value of $sum. The use of my ensures that the variables $x, $y, and $result are only visible within the add_numbers subroutine, and that the variables $a, $b, and $sum are only visible within the main program.