返回布尔值的 Perl 函数实际上返回什么 [英] What do Perl functions that return Boolean actually return

查看:33
本文介绍了返回布尔值的 Perl 函数实际上返回什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Perl defined 函数(以及许多其他函数)返回布尔值".

The Perl defined function (and many others) returns "a Boolean value".

鉴于 Perl 实际上没有布尔类型(并且使用像 1 这样的值来表示 true,以及 0undef for false) Perl 语言是否准确指定了布尔值返回的内容?例如,defined(undef) 会返回 0 还是 undef,是否会发生变化?

Given Perl doesn't actually have a Boolean type (and uses values like 1 for true, and 0 or undef for false) does the Perl language specify exactly what is returned for a Boolean values? For example, would defined(undef) return 0 or undef, and is it subject to change?

推荐答案

在几乎所有情况下(即除非有其他原因),Perl 返回两个静态分配的标量之一:&PL_sv_yes(真)和 &PL_sv_no(假).这是它们的详细信息:

In almost all cases (i.e. unless there's a reason to do otherwise), Perl returns one of two statically allocated scalars: &PL_sv_yes (for true) and &PL_sv_no (for false). This is them in detail:

>perl -MDevel::Peek -e"Dump 1==1"
SV = PVNV(0x749be4) at 0x3180b8
  REFCNT = 2147483644
  FLAGS = (PADTMP,IOK,NOK,POK,READONLY,pIOK,pNOK,pPOK)
  IV = 1
  NV = 1
  PV = 0x742dfc "1"
  CUR = 1
  LEN = 12

>perl -MDevel::Peek -e"Dump 1==0"
SV = PVNV(0x7e9bcc) at 0x4980a8
  REFCNT = 2147483647
  FLAGS = (PADTMP,IOK,NOK,POK,READONLY,pIOK,pNOK,pPOK)
  IV = 0
  NV = 0
  PV = 0x7e3f0c ""
  CUR = 0
  LEN = 12

yes 是一个三重变量(IOK、NOK 和 POK).它包含一个等于 1 的有符号整数 (IV)、一个等于 1 的浮点数 (NV) 和一个等于 1 的字符串 (PV).

yes is a triple var (IOK, NOK and POK). It contains a signed integer (IV) equal to 1, a floating point number (NV) equal to 1, and a string (PV) equal to 1.

no 也是一个三重变量(IOK、NOK 和 POK).它包含一个等于 0 的有符号整数 (IV)、一个等于 0 的浮点数 (NV) 和一个空字符串 (PV).这意味着它将字符串化为空字符串,并将其数字化为 0.它既不等同于空字符串

no is also a triple var (IOK, NOK and POK). It contains a signed integer (IV) equal to 0, a floating point number (NV) equal to 0, and an empty string (PV). This means it stringifies to the empty string, and it numifies to 0. It is neither equivalent to an empty string

>perl -wE"say 0+(1==0);"
0

>perl -wE"say 0+'';"
Argument "" isn't numeric in addition (+) at -e line 1.
0

也不到 0

>perl -wE"say ''.(1==0);"


>perl -wE"say ''.0;"
0

无法保证情况会一直如此.没有理由依赖于此.如果您需要特定的值,您可以使用类似

There's no guarantee that this will always remain the case. And there's no reason to rely on this. If you need specific values, you can use something like

my $formatted = $result ? '1' : '0';

这篇关于返回布尔值的 Perl 函数实际上返回什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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