Chinaunix首页 | 论坛 | 博客
  • 博客访问: 966611
  • 博文数量: 184
  • 博客积分: 10030
  • 博客等级: 上将
  • 技术积分: 1532
  • 用 户 组: 普通用户
  • 注册时间: 2005-12-27 18:32
文章分类

全部博文(184)

文章存档

2009年(1)

2008年(63)

2007年(39)

2006年(79)

2005年(2)

我的朋友

分类:

2007-01-04 11:48:42

在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
-------------------------------------------------------------------
 
阅读(2861) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~