Perl学习01之标量数据
目录
浮点数
整数
数字操作符
单引号(A single-quoted string literal)
双引号(A single-quoted string literal)
字符串操作符
重复操作符
数字与字符串之间的转换
变量命名规则
标量等号赋值
标量双目赋值符赋值
字符串变量内插
数值标量与字符标量比较操作符
chomp函数
chop函数
substr函数
split函数
-----------------------------------------------------------------------------
1 数字
浮点数
整数
#!/usr/bin/perl
use strict;
use warnings;
my $int1 = 1_415_926;
print "$int1\n";
perl int1.pl
数字操作符
#!/usr/bin/perl
my $compute_result = 10%4;
print "$compute_result\n";
perl compute.pl
----------------------------------------------------------------------------------
2 字符串
单引号(A single-quoted string literal)
#!/usr/bin/perl
use strict;
use warnings;
my $string1 = 'perl\t\n';
my $string2 = 'perl\\t\\n'; #此时\t \n分别表示tab键和换行符;
print "$string1\n";
print "$string2\n";
双引号(A single-quoted string literal)
#!/usr/bin/perl
use strict;
use warnings;
my $string1 = "perl\tperl1\n"; #\t表示tab,\n表示换行;
print "$string1\n";
字符串操作符
#!/usr/bin/perl
use strict;
use warnings;
my $string1 = "Come";
my $string2 = "on!";
my $string3 = $string1.$string2;
print "$string3\n";
print "$string1"." "."$string2"."\n";#string1 空格 string2
perl string3.pl
重复操作符
#!/usr/bin/perl
use strict;
use warnings;
my $string4 = "Comeon!\t"x3;
my $string5 = "Comeon!\t"x3.5;
print "$string4\n";
print "$string5\n";
数字与字符串之间的转换
#!/usr/bin/perl
use strict;
use warnings;
my $string6 = "12fred34" * "3";
my $string7 = "Z" . 5 * 7;
print "$string6\n";
print "$string7\n";
perl string5.pl
Argument "12fred34" isn't numeric in multiplication (*) at string6.pl line 5. #Perl会发出警告
----------------------------------------------------------------------------------
3 标量变量
变量命名规则
标量等号赋值
标量双目赋值符赋值
字符串变量内插
#!/usr/bin/perl
use strict;
use warnings;
my $string6 = "Lady cai";
my $string7 = "I like $string6 !";
print "$string7\n";
数值标量与字符标量比较操作符
数值标量 字符标量 含义
== eq 等于
!= ne 不等与
< lt 小于
> gt 大于
<= le 小于等于
>= ge 大于等于
chomp函数
#!/usr/bin/perl
use strict;
use warnings;
my $text = "Start from here\n";
print "$text\n";#此处会输出两个换行符
my $text1 = chomp ($text);
# 返回值为去掉的字符个数,去掉1个\n,所以输出为1
print "$text\n";#此处只输出一个换行符
print "$text1\n";
perl chomp1.pl
chop函数
#!/usr/bin/perl
use strict;
use warnings;
my $scalar1="Perl";
my $chop1=chop $scalar1;#返回去掉的值,修改原字符
print "$scalar1\n";
print "$chop1\n";
perl chop.pl
substr函数
#!/usr/bin/perl
use strict;
use warnings;
my $string="I love LadyCai";
my $substr1=substr $string,1;
my $substr2=substr $string,1,3;
my $substr3=substr $string,1,3,"XX";
print "$substr1\n";
print "$substr2\n";
print "$substr3\n";
print "$string\n";#原字符已改变
perl substr1.pl
split函数
If only PATTERN is given, EXPR defaults to $_ ;
PATTERN,分隔符,可以是正则,可以同时指定多个分隔符,defaults是
" ",
省略分隔符所有连续空白都会被当作单个分隔符;LIMIT,表示最多分割为几个元素,defaults为1,若则表示尽可能多地分隔。
#limit,限制分割次数
print join(':', split(//, 'abc', 1)), "\n"; #abc
print join(':', split(//, 'abc', 2)), "\n"; #a:bc
print join(':', split(//, 'abc', 3)), "\n"; #a:b:c
print join(':', split(//, 'abc', 4)), "\n"; #a:b:c
4 参考资料
https://perldoc.perl.org
小骆驼
后续还有更多优质文章,欢迎您关注我的公众号