文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>【Perl编程金典】Perl的返回值和wantarray()函数

【Perl编程金典】Perl的返回值和wantarray()函数

时间:2007-01-04  来源:yszll

在Perl中,来自子程序的返回值既可是一个标量,也可以是一个列表。另外,甚至可以让一个子程序的返回值变得“不确定”----一次调用既有可能返回一个列表,也有可能返回一个标量---具体由子程序的调用场合来决定。为支持这种不确定性,Perl专门提供了wantarray函数。 一旦在子程序主体中调用了这个函数,那么假如子程序是在一个列表试用场合下调用的,该函数便返回一个真值;假如子程序是在一个标量使用场合下调用的,该函数便返回一个假值。 ---------------------------------------------------------------------------------- #!/usr/bin/perl
# Fig 6.7: fig06_07.pl
# Demonstrating a subroutine that returns a scalar or a list.
# call scalarOrList() in list context to initialize @array,
# then print the list
@array = scalarOrList();  # list context to initialize @array
$" = "\n";                # set default separator character
print "Returned:\n@array\n";
# call scalarOrList() in scalar context and concatenate the
# result to another string
print "\nReturned: " . scalarOrList();  # scalar context
# use wantarray to return a list or scalar
# based on the calling context
sub scalarOrList
{
   if ( wantarray() ) {   # if list context
      return 'this', 'is', 'a', 'list', 'of', 'strings';
   }
   else {               # if scalar context
      return 'hello';
   }
}
    ------------------------------------------------------------------ 输出如下: Returned:
this
is
a
list
of
strings
Returned: hello -------------------------------------------------------------------  
相关阅读 更多 +
排行榜 更多 +
阿克里危机手机版下载

阿克里危机手机版下载

飞行射击 下载
贪婪洞窟重生手游下载

贪婪洞窟重生手游下载

角色扮演 下载
贡贡托儿所手机版下载

贡贡托儿所手机版下载

休闲益智 下载