0% found this document useful (0 votes)
3 views2 pages

Ex No 7 Com 313

Uploaded by

gopichandran2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Ex No 7 Com 313

Uploaded by

gopichandran2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Ex No.

8 Subroutines and functions in PERL


In Perl, subroutines and functions are used to group reusable code. The terms
"subroutine" and "function" are often used interchangeably in Perl, but typically,
subroutine refers to user-defined routines, and function refers to built-in ones.
1. Defining and Using Subroutines
A subroutine is defined using the sub keyword and called by its name with
optional arguments.
# Define a subroutine
sub greet {
my ($name) = @_; # Retrieve the first argument
print "Hello, $name!\n";
}

# Call the subroutine


greet("Alice");
greet("Bob");
Output:
Copy code
Hello, Alice!
Hello, Bob!
2. Returning Values from Subroutines
# Define a subroutine to calculate the square of a number
sub square {
my ($number) = @_;
return $number * $number;
}
# Call the subroutine and capture the result
my $result = square(5);
print "The square of 5 is $result\n";
Output:
The square of 5 is 25
If return is omitted, the last evaluated expression is returned.
3. Subroutines with Default Parameters
Perl does not have direct support for default arguments, but you can simulate
this using conditional checks.
# Define a subroutine with default arguments
sub greet_with_default {
my ($name) = @_;
$name = "Guest" unless defined $name; # Assign default value
print "Hello, $name!\n";
}
# Call the subroutine
greet_with_default("Alice");
greet_with_default(); # No arguments passed
Output:
Hello, Alice!
Hello, Guest!

You might also like