perl print array from subroutine
#! /usr/local/bin/perl
sub getClusters
{
my @clusters = `/qbo/bin/getclusters|grep -v 'qboc33'`;
chomp(@clusters);
return \@clusters;
}
ummm okay .. how do I get at this array to print since ...
foreach $cluster (getClusters())
{ print $cluster."\n"; }
doesn't seem to work.开发者_C百科 Thanks.
You are returning a reference, and not dereferencing it anywhere.
foreach $cluster (@{getClusters()})
OR
return @clusters;
Either should fix it (with slightly different effects), with the first one being preferred (your array is kind of big).
You'd use the non-referenced array return for limited number of elements, usually for the purpose of multi-return (thus, usually, limited to 2 or 3, known-length arrays).
If you ran your program under use strict; use warnings;
, it would have told you why it failed. As Amadan said, you need to dereference the reference you return.
Perl Solution
#!/usr/local/bin/perl
use strict;
use warnings;
main();
sub main{
{
local $" = "\n";
print "@{getClusters()}";
}
}
sub getClusters{
my @tArray = `/qbo/bin/getclusters|grep -v 'qboc33'`;
chomp @tArray;
return \@tArray;
}
Notice
- You don't need a
foreach
loop for debugging, you can just reset the$"
operator however to separate array elements however you like (eg,,
, or how I set it in the code above\n
). - Returning an array ref is a plus, don't send back the full array (good job)
- use strict/warnings, especially when debugging
- try to avoid system calls using
``
To make it easy, you can first receive the return value and then print it like
use strict;
use warning;
my $cluster_array = getClusters();
my @cluster_return = @{$cluster_array};
foreach my $cluster(@cluster_return){
print"$cluster\n";
}
精彩评论