Perl中的wantarray()函数如果当前正在执行的子例程希望返回列表值,则返回True,如果正在寻找标量值,则返回false。
用法: wantarray()
返回值:列表值为true,标量值为false
示例1:
#!/usr/bin/perl -w
# Subroutine to call wantarray() function
sub geeks
{
return(wantarray() ? ("Geeks", "For", "Geeks") : 1);
}
# Calling the subroutine
# in scalar and array context
$value = geeks();
@value = geeks();
# Printing the values in both contexts
print("Value in Scalar context: $value\n");
print("Value in List Context: @value");
输出:
Value in Scalar context: 1 Value in List Context: Geeks For Geeks
示例2:
#!/usr/bin/perl -w
# Subroutine to call wantarray() function
sub geeks
{
if(wantarray())
{
# Addition of two numbers when
# wantarray() function is called
# in list context
$c = $a + $b;
}
else
{
# When wantarray() is called
# in Scalar context
return 1;
}
}
# Driver Code
$a = 10; $b = 20; $c = 0;
# Calling Subroutine in scalar and list contexts
$value = geeks($a, $b);
@value = geeks($a, $b);
# Printing values in both the contexts
print("Value when called in Scalar context: $value\n");
print("Value when called in List Context: @value");
输出:
Value when called in Scalar context: 1 Value when called in List Context: 30
相关用法
- Perl ord()用法及代码示例
- Perl int()用法及代码示例
- Perl uc()用法及代码示例
- Perl each()用法及代码示例
- Perl oct()用法及代码示例
- Perl cos()用法及代码示例
- Perl log()用法及代码示例
- Perl sin()用法及代码示例
- Perl exp用法及代码示例
- Perl tell()用法及代码示例
- Perl hex用法及代码示例
- Perl abs()用法及代码示例
- Perl chr()用法及代码示例
- Perl reverse()用法及代码示例
- Perl rindex()用法及代码示例
注:本文由纯净天空筛选整理自Code_Mech大神的英文原创作品 Perl | wantarray() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。