Perl Learning: 2.10. The undef Value

Previous Page
Next Page

 

2.10. The undef Value

What happens if you use a scalar variable before you give it a value? Nothing serious and definitely nothing fatal. Variables have the special undef value before they are first assigned, which is Perl's way of saying "nothing here to look atmove along, move along." If you use this "nothing" as a "numeric something," it will act like zero. If you use it as a "string something," it will act like the empty string. But undef is neither a number nor a string; it's an entirely separate kind of scalar value.

Because undef automatically acts like zero when used as a number, it's easy to make an numeric accumulator that starts out empty:

    # Add up some odd numbers
    $n = 1;
    while ($n < 10) {
      $sum += $n;
      $n += 2; # On to the next odd number
    }
    print "The total was $sum./n";

This works properly when $sum was undef before the loop started. The first time through the loop, $n is one, so the first line inside the loop adds one to $sum. That's like adding 1 to a variable that already holds zero because you're using undef as if it were a number. Now it has the value 1. After that, since it's been initialized, adding works in the traditional way.

Similarly, you could have a string accumulator that starts out empty:

    $string .= "more text/n";

If $string is undef, this will act as if it already held the empty string, putting "more text/n" into that variable. But if it holds a string, the new text is appended.

Perl programmers frequently use a new variable in this way, letting it act as zero or the empty string as needed.

Many operators return undef when the arguments are out of range or don't make sense. If you don't do anything special, you'll get a zero or a null string without major consequences. In practice, this is hardly a problem. In fact, most programmers rely upon this behavior. But you should know that when warnings are turned on, Perl will typically warn about unusual uses of the undefined value since that may indicate a bug. For example, copying undef from one variable into another isn't a problem, but trying to print it would generally cause a warning.

Previous Page
Next Page
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值