Perl (Scripting) - return an array

by
Jeremy Canfield |
Updated: March 26 2021
| Perl (Scripting) articles
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 array in the greeting subroutine contains "Hello World", and then the @foo array is returned.
#!/usr/bin/perl
use strict;
use warnings;
sub greeting {
my @foo = qw(Hello World);
return @foo;
}
Outside of the subroutine, the output of the greeting subroutine is stored in the @bar array.
my @bar = greeting();
print "@bar \n";
Running this script will output the following.
Hello World
Be aware that when a subroutine is returning an array, you wouldn't want to store the results in a variable.
my $count = greeting();
print "$count \n";
As this would return the count, which would be 2 in this example, since there are 2 elements in the array (Hello and World).
Did you find this article helpful?
If so, consider buying me a coffee over at