Forum

Learn Perl Function…
 
Notifications
Clear all

Learn Perl Functions

1 Posts
1 Users
0 Reactions
10 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

 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");

 


   
Quote
Share: