函数返回数组 [英] Function returning array
问题描述
我试图从子程序返回一个数组并使用另一个子程序。当我这样做时它什么都不打印。
# !/ usr / bin / perl
使用 strict;
se警告;
# 子程序原型
sub getArray();
# 获取数组
sub dispArray
{
my @ one =的getArray();
print $ one [1] \\ \
跨度>;
}
sub getArray()
{
my @ array1 =( a , b, c, d);
return @ array1 ;
}
但是当我这样做时工作正常,即不从另一个子程序调用它
# !/ usr / bin / perl
使用 strict;
se警告;
# 子程序原型
sub getArray();
# 获取数组
my @ one = getArray();
print $ one [1] \\ \
跨度>;
sub getArray()
{
my @ array1 =( a, b, c, d);
return @ array1 ;
}
背后的原因是什么?我怎么能通过从另一个子例程中调用getArray()来正确实现它。任何帮助将不胜感激。
one [1] \ n;
}
sub getArray()
{
my @ array1 =( a, b, c , d);
return @ array1 ;
}
但是当我这样做时工作正常,即不从另一个子程序调用它
< span class =code-comment># !/ usr / bin / perl
use strict;
警告;
# 子程序原型
sub getArray();
# 获取数组
my @ one = getArray();
[1] \\\
跨度>;
sub getArray()
{
my @ array1 =( a, b, c, d);
return @ array1 ;
}
背后的原因是什么?我怎么能通过从另一个子例程中调用getArray()来正确实现它。任何帮助将不胜感激。
尝试避免原型,以下将通过检查调用者想要的内容每次产生您想要的结果。
#!/ usr / bin / perl
使用严格;
使用警告;
sub getArray()
{
my @ array1 =(a,b,c,d);
返回@ array1 if wantarray;
返回\ @ array1;
}
#获取数组
sub dispArray
{
my @one = getArray();
I am trying to return an array from a subroutine and use it another subroutine. It prints nothing when I do this.
#!/usr/bin/perl
use strict;
se warnings;
# Subroutine prototypes
sub getArray();
# Get array
sub dispArray
{
my @one = getArray();
print "$one[1]\n";
}
sub getArray()
{
my @array1 = ("a", "b", "c", "d");
return @array1;
}
But works fine when I do this i.e not calling it from another sub routine
#!/usr/bin/perl
use strict;
se warnings;
# Subroutine prototypes
sub getArray();
# Get array
my @one = getArray();
print "$one[1]\n";
sub getArray()
{
my @array1 = ("a", "b", "c", "d");
return @array1;
}
What is the reason behind it and how can I implement it correctly by calling getArray() from within another sub routine. Any help will be appreciated.
one[1]\n"; } sub getArray() { my @array1 = ("a", "b", "c", "d"); return @array1; }
But works fine when I do this i.e not calling it from another sub routine
#!/usr/bin/perl use strict; se warnings; # Subroutine prototypes sub getArray(); # Get array my @one = getArray(); print "
one[1]\n"; sub getArray() { my @array1 = ("a", "b", "c", "d"); return @array1; }
What is the reason behind it and how can I implement it correctly by calling getArray() from within another sub routine. Any help will be appreciated.
Try to avoid prototypes and the following will yield the result you want every time by also checking what the caller wants.
#!/usr/bin/perl use strict; use warnings; sub getArray() { my @array1 = ("a", "b", "c", "d"); return @array1 if wantarray; return \@array1; } # Get array sub dispArray { my @one = getArray(); print "
这篇关于函数返回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!