當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Perl wantarray()用法及代碼示例


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


相關用法


注:本文由純淨天空篩選整理自Code_Mech大神的英文原創作品 Perl | wantarray() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。