在 Perl 中,可以使用数组名称来引用数组吗?
我是 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";
}
}
}
}
寻求与此类似的较短代码:
sub print_species_names {
my $species = shift(@_);
my @cats = ("Jeffry", "Owen");
my @dogs = ("Duke", "Lassie");
foreach (@<$species>) {
print $_ . "\n";
}
}
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";
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可能的?是的。受到推崇的? 不。一般来说,使用符号引用是不好的做法。相反,使用哈希来保存数组。这样您就可以按名称查找它们:
如果您想进一步减少名称,您可以将 if/else 块替换为:
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:
您可以通过使用数组引用的哈希来实现接近的目标:
You can achieve something close by using a hash of array references:
您也可以在这里使用 eval:
我应该明确表示您需要关闭严格引用才能使其工作。因此,使用“nostrict”和“strict”来包围代码是有效的。
这就是 Perl 中的软引用。
You could also use eval here:
I should have made it clear that you need to turn off strict refs for this to work. So surrounding the code with use "nostrict" and use "strict" works.
This is whats known as a soft reference in perl.