perl function sub
In Perl, sub
is used to define subroutines, which are blocks of code that can be called from other parts of the program. Here's an example of using the sub
function to define a simple subroutine:
sub greet { my $name = shift; print "Hello, $name!\n"; } greet("Alice"); # Prints "Hello, Alice!" greet("Bob"); # Prints "Hello, Bob!"
In this example, we define a subroutine called greet
that takes a single argument $name
. The shift
function is used to get the first argument passed to the subroutine.
The body of the greet
subroutine simply prints a greeting message with the name passed as an argument.
We then call the greet
subroutine twice with different names, and each time it prints a greeting message with the appropriate name.
Subroutines can also have return values, which can be useful for passing data back to the calling code. Here's an example of a subroutine that returns the sum of two numbers:
sub add { my ($x, $y) = @_; return $x + $y; } my $result = add(2, 3); # $result is now 5
In this example, we define a subroutine called add
that takes two arguments $x
and $y
. The @_
array is used to get all of the arguments passed to the subroutine, and we use list assignment to assign them to $x
and $y
.
The body of the add
subroutine simply returns the sum of $x
and $y
.
We then call the add
subroutine with the values 2
and 3
, and assign the result to the variable $result
. The value of $result
is now 5
, which is the sum of 2
and 3
.