Learning Perl: 4.10. Non-Scalar Return Values

Previous Page
Next Page

 

4.10. Non-Scalar Return Values

A scalar isn't the only kind of return value a subroutine may have. If you call your subroutine in a list context,[] it can return a list of values.

[] You can detect if a subroutine is being evaluated in a scalar or list context using the wantarray function, which lets you easily write subroutines with specific list or scalar context values.

Suppose you wanted to get a range of numbers (as from the range operator, ..) except that you want to be able to count down as well as up. The range operator only counts upward, but that's easily fixed:

    sub list_from_fred_to_barney {
      if ($fred < $barney) {

        # Count upwards from $fred to $barney
        $fred..$barney;
      } else {
        # Count downwards from $fred to $barney
        reverse $barney..$fred;
      }
    }
    $fred = 11;
    $barney = 6;
    @c = &list_from_fred_to_barney; # @c gets (11, 10, 9, 8, 7, 6)

In this case, the range operator gives us the list from 6 to 11, and reverse reverses the list, so it goes from $fred (11) to $barney (6) just as we wanted.

The least you can return is nothing at all. A return with no arguments will return undef in a scalar context or an empty list in a list context. This can be useful for an error return from a subroutine, signalling to the caller that a more meaningful return value is unavailable.

Previous Page
Next Page
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值