FreeKB - Perl (Scripting) return a variable
Perl (Scripting) - return a variable

If you are not familiar with subroutines, check out our article on Perl - Getting Started with Subroutines.

Let's say you have the following script. In this example, the $foo variable in the greeting subroutine contains "Hello World" and then the $foo variable is returned.

use strict;
use warnings;

sub greeting {
  my $foo = "Hello World";
  return $foo;


Outside of the subroutine, the output of the greeting subroutine is stored in the $bar variable.

my $bar = greeting();


You could then print the $bar variable.

print "$bar \n";


Which would return the following.

Hello World


Likewise, you could store the output of the greeting subroutine in an array.

Here is how to return two (or more) variables.

sub greeting {
  my $foo = "Hello";
  my $bar = "World";
  return ($foo, $bar);


When returning two (or more) values, you'll want to store the output in an array.

my @foo = greeting();


You could then print the @foo array.

print "@foo \n";


Which should also output Hello World.

Hello World

Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter 77fe4 in the box below so that we can be sure you are a human.


Web design by yours truely - me, myself, and I   |   |