Notifications
Clear all
Topic starter 01/08/2025 11:36 pm
Perl functions—often called subroutines—are blocks of reusable code that help you organize and simplify your program. Here’s how they work:
🔧 Defining a Function in Perl
- Use the
sub
keyword followed by the function name and a code block{}
sub greet {
print "Hello, world!\n";
}
- To call that function:
greet(); # prints "Hello, world!"
📦 Passing Arguments
- Arguments are passed using the special array
@_
- Inside the function, you can access them directly or assign them to variables:
sub greet_person {
my ($name) = @_;
print "Hello, $name!\n";
}
greet_person("Alice"); # prints "Hello, Alice!"
🔁 Returning Values
- Use
return
to send data back from a function
sub square {
my ($num) = @_;
return $num * $num;
}
my $result = square(4); # $result is 16
🎨 More Examples
- Multiple arguments:
sub add {
my ($a, $b) = @_;
return $a + $b;
}
print add(3, 5); # prints 8
- Return list:
sub split_name {
my ($full_name) = @_;
return split(' ', $full_name);
}
my ($first, $last) = split_name("Ada Lovelace");