来自子程序的perl打印数组

Sim*_*eth 0 arrays perl foreach subroutine

#! /usr/local/bin/perl 
sub getClusters
{
my @clusters = `/qbo/bin/getclusters|grep -v 'qboc33'`;
chomp(@clusters);
return \@clusters;
}
Run Code Online (Sandbox Code Playgroud)

嗯好吧..我怎么得到这个阵列打印,因为......

foreach $cluster (getClusters())
{ print $cluster."\n"; }
Run Code Online (Sandbox Code Playgroud)

似乎不起作用.谢谢.

Ama*_*dan 5

您正在返回引用,而不是在任何地方取消引用它.

foreach $cluster (@{getClusters()})
Run Code Online (Sandbox Code Playgroud)

要么

return @clusters;
Run Code Online (Sandbox Code Playgroud)

要么修复它(效果略有不同),第一个是首选(你的数组有点大).

您将使用非引用数组返回有限数量的元素,通常用于多次返回(因此,通常,限制为2或3,已知长度数组).

  • +1.返回数组没有任何问题.有许多事情需要考虑,例如典型的数组大小,以及sub在上下文中的行为方式. (2认同)