Perl 布尔值

Perl 布尔值

在大多数编程语言中,True 和 False 被认为是布尔值。但是Perl并没有为True和False提供布尔类型。一般来说,当一个函数返回True或False时,程序员可以使用 “布尔值 “这一术语。就像条件语句(if, while, 等)会返回标量值的真或假。

例子

# Perl Code to demonstrate the boolean values
 
# variable assigned value 0
k = 0;
 
# checking whether k is true or false
if (k)
{
    print "k is True\n";
}
else
{
    print "k is False\n";
}
 
# variable assigned value 2
m = 2;
 
# checking whether m is true or false
if (m)
{
    print "m is True\n";
}
else
{
    print "m is False\n";
}

输出

k is False
m is True

真值: 在Perl语言中,任何非零的数字,即除了零以外,都是真值。字符串常量如 ‘true’、 ‘false ‘、 ” (以空格为字符的字符串)、 ’00 ‘(2个或更多的0字符)和 “0/n “(字符串中一个0后的换行字符)等,在Perl中也被视为真值。

例子

# Perl Code to demonstrate the True values
 
# variable assigned value 5
a = 5;
 
# checking whether a is true or false
if (a)
{
    print "a is True\n";
}
else
{
    print "a is False\n";
}
 
# string variable assigned white
# space character
b = ' ';
 
# checking whether b is true or false
if (b)
{
    print "b is True\n";
}
else
{
    print "b is False\n";
}
 
# string variable assigned 'false'
# value to it
c = 'false';
 
# checking whether c is true or false
if (c)
{
    print "c is True\n";
}
else
{
    print "c is False\n";
}
 
# string variable assigned "0\n"
# value to it
d = "0\n";
 
# checking whether d is true or false
if (d)
{
    print "d is True\n";
}
else
{
    print "d is False\n";
}

输出

a is True
b is True
c is True
d is True

假值:空字符串或包含单数的0或undef值和0被认为是perl中的假值。

例子

# Perl Code to demonstrate the False values
 
# variable assigned value 0
a = 0;
 
# checking whether a is true or false
if (a)
{
    print "a is True\n";
}
else
{
    print "a is False\n";
}
 
# string variable assigned empty string
b = '';
 
# checking whether b is true or false
if (b)
{
    print "b is True\n";
}
else
{
    print "b is False\n";
}
 
# string variable assigned undef
c = undef;
 
# checking whether c is true or false
if (c)
{
    print "c is True\n";
}
else
{
    print "c is False\n";
}
 
# string variable assigned ""
# value to it
d = "";
 
# checking whether d is true or false
if (d)
{
    print "d is True\n";
}
else
{
    print "d is False\n";
}

输出

a is False
b is False
c is False
d is False

注: 对于用户需要比较两个不同变量的条件检查,如果它们不相等,则返回 False ,否则返回 True。

例子

# Perl Program demonstrate the conditional check
 
# variable initialized with string
x = "GFG";
 
# using if statement
if (x eq "GFG")
{
    print "Return True\n";
}
else
{
    print "Return False\n";
}

输出

Return True

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程