Perl Cd Bookshelf [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Perl Cd Bookshelf [Electronic resources] - نسخه متنی

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید



10.6. Detecting Return Context


10.6.1. Problem



You want to know in which context your
function was called. This lets one function do different things,
depending on how its return value or values are used, just like many
of Perl's built-in functions.

10.6.2. Solution


Use the wantarray( ) function, which has three
possible return values, depending on how the current function was
called:

if (wantarray( )) {
# list context
}
elsif (defined wantarray( )) {
# scalar context
}
else {
# void context
}

10.6.3. Discussion


Many built-in functions act differently when called in scalar context
than they do when called in list context. A user-defined function can
learn which context it was called in by checking
wantarray. List context is indicated by a true
return value. If wantarray returns a value that is
false but defined, then the function's return value will be used in
scalar context. If wantarray returns
undef, your function isn't being asked to provide
any value at all.

if (wantarray( )) {
print "In list context\n";
return @many_things;
} elsif (defined wantarray( )) {
print "In scalar context\n";
return $one_thing;
} else {
print "In void context\n";
return; # nothing
}
mysub( ); # void context
$a = mysub( ); # scalar context
if (mysub( )) { } # scalar context
@a = mysub( ); # list context
print mysub( ); # list context

10.6.4. See Also


The return and wantarray
functions in Chapter 29 of Programming Perl
and in perlfunc(1)



10.5. Passing Arrays and Hashes by Reference10.7. Passing by Named Parameter




Copyright © 2003 O'Reilly & Associates. All rights reserved.

/ 875