Perl教程
Perl控制语句
Perl高级

Perl 标量

Perl 标量

标量包含单个数据单元。它以($) 符号开头,后跟字母、数字和下划线。
标量可以包含任何数字、浮点数、字符或字符串。
我们可以通过两种方式定义标量。首先,我们可以一起声明和赋值。其次,我们将首先声明,然后为标量赋值。
在下面的示例中,我们将展示定义标量的两种方法。
示例:
use strict;
use warnings;
use 5.010;
#Declairing and assigning value together
my $color = "Red";
say $color;
#Declairing the variable first and then assigning value
my $city;
$city = "Delhi";
say $city;
输出:
Red
Delhi

Perl 标量运算

在本例中,我们将使用两个标量变量 $x 和 $y 执行不同的运算>.在 Perl 中,运算符告诉操作数如何表现。
示例:
use strict;
use warnings;
use 5.010;
my $x = 5;
say $x;             
my $y = 3;
say $y;            
say $x + $y;        
say $x . $y;        
say $x x $y;
输出:
5
3
8
53
555
第一个和第二个输出分别是 $x 和 $y 的值。
(+) 运算符简单地将 5 和 3 相加,输出为 8、
(.) 是一个连接运算符,它将输出 5 和 3 连接起来,输出为 53、
(x)是一个重复运算符,它重复左侧变量的次数与其右侧的数字一样多。

Perl 特殊文字

Perl 中有三个特殊文字:
__FILE__ : 代表当前文件名。
__LINE__ : 代表当前行号。
__PACKAGE__ : 代表那个时候的包名在您的程序中。
示例:
use strict;
use warnings;
use 5.010;
#!/usr/bin/perl
print"File name ". __FILE__ . "\n";
print"Line Number " . __LINE__ ."\n";
print"package " . __PACKAGE__ ."\n";
# they can?t be interpolated
print"__FILE__ __LINE__ __PACKAGE__\n";
输出:
File name hw.pl
Line Number 6
package main
__FILE__ __LINE __ __PACKAGE

Perl 字符串上下文

Perl 根据需要自动将字符串转换为数字,将数字转换为字符串。
例如, 5 与"5" 相同,5.123 与"5.123" 相同。
但是如果字符串包含数字以外的某些字符,它们在算术运算中的表现如何。让我们通过一个例子来看看。
例子:
use strict;
use warnings;
use 5.010;
my $x = "5";
my $y = "2cm";
say $x + $y;       
say $x . $y;      
say $x x $y;
输出:
7
52cm
55
在数字上下文中,Perl 查看字符串的左侧,并将其转换为数字。字符成为变量的数值。在数字上下文(+) 中,给定的字符串 "2cm" 被视为数字 2、
尽管它会生成警告为
Argument "2cm" isn't numeric in addition (+) at hw.pl line 9.
这里发生的事情是,Perl 不会将 $y 转换为数值。它只是使用了它的数字部分,即; 2.

Perl undef

如果你不在变量中定义任何东西,它被认为是undef。在数字上下文中,它充当 0。在字符串上下文中,它充当空字符串。
use strict;
use warnings;
use 5.010;
my $x = "5";
my $y;
say $x + $y;       
say $x . $y;      
say $x x $y;
if (defined $y) {
  say "defined";
} else {
  say "NOT";         
}
输出:
Use of uninitialized value $y in addition (+) at hw.pl line 9.
5
Use of uninitialized value $y in concatenation (.) or string at hw.pl line 10.
5
Use of uninitialized value $y in repeat (x) at hw.pl line 11.
NOT
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4