WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Perl · Basic · question 5 of 100

What is a subroutine in Perl, and how do you create and call one?

📕 Buy this interview preparation book: 100 Perl questions & answers — PDF + EPUB for $5

In Perl, a subroutine is a self-contained block of code that performs a specific task, and it can be called multiple times from within a program. Subroutines are used to structure code, make code more modular, and to avoid repeating code.

You can create a subroutine in Perl using the ‘sub‘ keyword, followed by the name of the subroutine, and a block of code enclosed in curly brackets. Here’s an example:

sub greet {
  my $name = shift;
  print "Hello, $name!n";
}

In this example, we’ve defined a ‘greet‘ subroutine that takes one argument (‘$name‘) and prints a greeting message. The ‘shift‘ function is used to extract the first argument passed to the subroutine, and assign it to the ‘$name‘ variable.

To call a subroutine in Perl, you simply need to use its name, followed by any required arguments in parentheses. Here’s an example:

greet("Alice");

When this line of code is executed, the ‘greet‘ subroutine is called with the argument "Alice". The output would be: "Hello, Alice!".

You can also define a subroutine without any arguments. For example:

sub hello {
  print "Hello, world!n";
}

In this case, you can call the subroutine simply by using its name, without any arguments:

hello();

The output would be: "Hello, world!".

Subroutines can also return values using the ‘return‘ keyword. Here’s an example:

sub add {
  my ($a, $b) = @_;
  my $result = $a + $b;
  return $result;
}

In this example, we’ve defined an ‘add‘ subroutine that takes two arguments (‘$a‘ and ‘$b‘), adds them together, and returns the result. The ‘@_‘ array is used to extract the arguments passed to the subroutine, and assign them to the ‘$a‘ and ‘$b‘ variables.

To use the ‘add‘ subroutine and capture its return value, we can do the following:

my $sum = add(2, 3);
print "The sum is $sumn";

The output would be: "The sum is 5".

In summary, subroutines are essential to modularize the code and avoid redundancy, in Perl we define a subroutine using the ‘sub‘ keyword followed by the name of the subroutine and the implementation between curly braces. We call a subroutine by using the subroutine’s name followed by the arguments within parentheses. Finally, we can return values from subroutines using the ‘return‘ keyword.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Perl interview — then scores it.
📞 Practice Perl — free 15 min
📕 Buy this interview preparation book: 100 Perl questions & answers — PDF + EPUB for $5

All 100 Perl questions · All topics