Subroutines and Context

Argument passing, subroutine definition, return values—these are the features of function definitions in any language. But, because this is Perl, there are always wrinkles. You already saw one of those wrinkles with the fact that individual arrays and hashes lose their identities when they're passed into subroutines as arguments. Another wrinkle is the issue of context.

Given that subroutines can be called in either a scalar or list context, and that they can return either a scalar or a list, context is a relevant issue to subroutine development. Or at least it's a relevant issue to keep in mind as you use your subroutines: be careful not to call subroutines that return lists in a scalar context, unless you're aware of the result and know how lists behave in that particular context.

There are the occasions, however, when you want to write a subroutine that will behave differently based on the context in which it was called (a very Perl-like thing to do). That's where the built-in wantarray function comes in. You use wantarray to find out the context in which your subroutine was called in. wantarray returns true if your subroutine was called in a list context; false if it was called in a scalar context (a more proper name might be “wantlist,” but it is called wantarray for historical reasons). So, for example, you might test for the context of your subroutine before returning a value, and then do the right thing based on that context, like this:

sub arrayorlist {
    # blah blah
    if (wantarray()) {
        return @listhing;
    } else { return $scalarthing }
}

Be careful with this feature, however. Keep in mind that just as functions that do different things based on context can be confusing (and may sometimes require a check of the documentation to figure out what they do), subroutines that do different things based on context can be doubly confusing. In many cases it's better to just return an appropriate value for the subroutine itself, and then deal with that value appropriately in the statement that called the subroutine in the first place.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset