I'm new to Perl and I understand you can call functions by name, like this:
&$functionName();
. However, I'd like to use an array by name. Is this possible?
Long code:
sub print_species_names {
my $species = shift(@_);
my @cats = ("Jeffry", "Owen");
my @dogs = ("Duke", "Lassie");
switch ($species) {
case "cats" {
foreach (@cats) {
print $_ . "\n";
}
}
case "dogs" {
foreach (@dogs) {
print $_ . "\n";
}
}
}
}
Seeking shorter code similar to this:
sub print_species_names {
my $species = shift(@_);
my @cats = ("Jeffry", "Owen");
my @dogs = ("Duke", "Lassie");
foreach (@<$species>) {
print $_ . "\n";
}
}
Possible? Yes. Recommended? No. In general, using symbolic references is bad practice. Instead, use a hash to hold your arrays. That way you can look them up by name:
If you want to reduce that even more, you could replace the if/else block with: