0
点赞
收藏
分享

微信扫一扫

Perl标量数据&布尔值

M4Y 2022-01-15 阅读 55

双目操作符

Perl中任何运算符都可以用双目操作符

$a+=5----->$a=$a+5
$a*=5----->$a=$a*5
$string.="hello"----->$string=$string."hello"

关系操作符

Perl中数据和字符串均可进行比较

数据的关系操作符字符串的关系操作符
==eq
!=ne
<lt
>gt
<=le
>=ge
<=>cmp(飞船操作符)

飞船操作符
数字:<=>
result = num1<=>num2
#num1< num2-----> result=-1
#num1> num2-----> result=1
#num1= num2-----> result=0
字符串:cmp
sresult = sting1 cmp string2
#string1 lt string2-----> sresult=-1
#string1 gt string2----> sresult=1
#string1 eq string2—> sresult=0

chomp函数

chomp函数:删除字符串末尾的一个“\n”,函数返回值为;
如果chomp函数发现字符串末尾有"\n",会将其删除;如果发现字符串末尾没有“\n”,则不会对字符串进行操作

$a="hello\n";
$b=chomp($a); 
#chomp($a)-->chomp$a,括号可以不写,perl是较为灵活的语言
#$b----->,函数返回值是1
#一般chomp函数的返回值都无用,一般直接写:chomp($a)
print $b."\n";
print $a;

chomp函数
chomp函数的应用场景:获取用户输入时,用于删除“\n”

print "please enter your name:"." ";
chomp($name=<STDIN>);
#<STDIN>:键盘输入;
#用户在输入界面输入数据后,会敲回车(即:“\n”)
#使得$name="string(输入)\n",使用chomp删除“\n”
print $name.","."welcom!"

运行结果为:
chomp函数运行结果

while结构

perl中的while循环和其他编程语言的while循环类似。

undef值

undef:表示未定义值,存在两种情况:
1.数据的undef:编译器会将undef按照0来处理

print $x+1#---->运行结果为:1
#$x为undef值,编译器按照0来处理

2.字符串的undef:编译器会将undef按照空字符串来处理,即:“”

print “hello”.$s."perl";#---->运行结果为:helloperl
#$s为undef值,编译器按照空字符串来处理
#注:空字符串不是空格,即:"" ne " "

defined函数

defined函数:用于检测变量是否undef,defined+undef用于检测是否读到文件末尾。

chomp($filestop=<STDIN>);
if(defined($filestop)){
  print "The end of the file has not been reached\n";
}#perl中if-else语句需要大括号
else{#在文件末尾就没有输入了,处于undef状态
  print "The end of the file is reached\n";
}

布尔值

perl中存在两种情况的布尔值:
1.如果为数字,则0为假,其余数字为真
2.如果为字符串,则空字符串为假,其余字符串为真,注:‘0’/"0"为假
3.如果不是数字或字符串,则先转换为数字或字符串再判断,如:undef为假
注:关系操作符中,如果为真返回1,否则返回空字符串

举报

相关推荐

0 条评论