函数返回数组 [英] Function returning array

查看:124
本文介绍了函数返回数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从子程序返回一个数组并使用另一个子程序。当我这样做时它什么都不打印。



  !/ 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();
print


[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();
print


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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆