为什么 Perl 中的“0"是假的? [英] Why is '0' false in Perl?

查看:72
本文介绍了为什么 Perl 中的“0"是假的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我来自C、Java、Python背景.最近,我开始为我的新工作学习 Perl,我对 '0' (0-string) 是假的感到好奇.

First of all, I come from C, Java, Python background. Recently, I started learning Perl for my new job and I got curious about '0' (0-string) being false.

我已经读到这种特殊行为是 Perl 必须使用 <> 操作符来读取文件的原因,所以对我来说这更像是一个设计缺陷,而不是现在的任何事情.但是,我也知道 Perl 是一种成熟的语言,我猜这种行为有其用途,否则它早就被修复了.

I've read that this particular behaviour is the reason why Perl had to have <> operator for reading files so it feels more like a design flaw to me than anything right now. However, I also know that Perl is a mature language and I am guessing this behaviour has its uses otherwise it would have been fixed long time ago.

那么在什么情况下 '0' = false 会有用?

So in what cases would '0' = false be useful?

推荐答案

Perl 没有明确的类型,它对类型的解释高度依赖于上下文.例如:

Perl has no explicit typing, and its interpretation of type is highly context-dependent. For example:

$a = "2b";
$b = "3a";
$c = $a + $b;
print $c;

产量为 5.

另一方面...

$a = "b2";
$b = "3a";
$c = $a + $b;
print $c;

产量为 3.

还有……

$a = "b2";
$b = "3a";
$c = $a.$b;
print $c;

产量 b23a

所以 "'0' (string)" 不是字符串、数字或布尔值,直到你使用它,然后它可以是任何这些东西,由它的用途决定.在您尝试操作之前,类型是不确定的.然后 Perl 评估上下文以实现您的意图并相应地采取行动.这是一个特性,以及为什么在 Perl 中有许多方法可以做事.它当然会导致大量令人困惑的代码,但非常适合 1-liners、混淆和 Perl 高尔夫.

So "'0' (string)" is not a string, or a number, or a bool, until you use it, and then it can be any of those things, determined by its use. Type is not determined until you try to operate. Then Perl assesses the context to endeavour your intention and acts accordingly. This is a Feature, and why there are Many Ways to Do Things in Perl. It can of course lead to a plenty of confusing code but is excellent for 1-liners, obfuscation and Perl golf.

这篇关于为什么 Perl 中的“0"是假的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆