在Perl中,可以使用其名称引用数组吗?

Ada*_*m S 1 perl symbolic-references

我是Perl的新手,我知道你可以按名称调用函数,如下所示: &$functionName();.但是,我想按名称使用数组.这可能吗?

长码:

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";
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

寻求类似于此的更短代码:

sub print_species_names {
    my $species = shift(@_);
    my @cats = ("Jeffry", "Owen");
    my @dogs = ("Duke", "Lassie");

    foreach (@<$species>) {
        print $_ . "\n";
    }
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*rom 15

可能?是.推荐的?.通常,使用符号引用是不好的做法.相反,使用哈希来保存数组.这样你可以按名称查找它们:

sub print_species_names {
    my $species = shift;
    my %animals = (
        cats => [qw(Jeffry Owen)],
        dogs => [qw(Duke Lassie)],
    );
    if (my $array = $animals{$species}) {
        print "$_\n" for @$array
    }
    else {
        die "species '$species' not found"
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你想减少更多,你可以用以下内容替换if/else块:

    print "$_\n" for @{ $animals{$species}
        or die "species $species not found" };
Run Code Online (Sandbox Code Playgroud)