Perl从多种语言中借用了语法和概念:awk,sed,C,Bourne Shell,Smalltalk,Lisp。但是,两种语言之间存在一定的区别。本章旨在使您快速掌握Perl中的语法。
Perl程序由一系列声明和语句组成,从顶部到底部,每个简单的语句必须以分号(;)结尾。
您可以在命令行中将Perl解释器与 -e 选项一起使用,从而可以从命令行执行Perl语句。让我们在$提示符下尝试以下操作-
$perl -e 'print "Hello World\n"'
该执行将产生以下输出-
Hello, world
假设您已经在$提示符下,让我们使用vi或vim编辑器打开文本文件hello.pl,并将以下行放入文件中。
#!/usr/bin/perl # This will print "Hello, World" print "Hello, world\n";
这里/usr/bin/perl 是实际的perl解释器二进制文件。在执行脚本之前,请确保更改脚本文件的模式并赋予执行特权,通常将设置0755权限,最后您可以如下执行上述脚本:
$chmod 0755 hello.pl $./hello.pl
该执行将产生以下输出-
Hello, world
您可以对函数参数使用括号,也可以根据自己的喜好忽略它们。以下两个语句产生相同的输出。
print("Hello, world\n"); print "Hello, world\n";
按照Perl约定,必须以.pl或.PL文件扩展名保存Perl文件,才能将其识别为Perl脚本。文件名可以包含数字,符号和字母,但不能包含空格。在空格处使用下划线(_)。
注释可用于使程序易于使用,并且解释器仅会跳过注释而不会影响代码函数。如在上述程序中,以哈希#开头的行是注释。
简单地说,Perl中的注释以井号开始并一直到行尾-
# This is a comment in perl
以=开头的行被解释为多行注释的开始,编译器将忽略直到下一个= cut的所有后续行,以下是示例-
#!/usr/bin/perl # This is a single line comment print "Hello, world\n"; =begin comment This is all part of multiline comment. You can use as many lines as you like These comments will be ignored by the compiler until the next =cut is encountered. =cut
这将产生以下输出-
Hello, world
Perl程序不关心空格。以下程序工作正常-
#!/usr/bin/perl print "Hello, world\n";
但是,如果在带引号的字符串中包含空格,则将按原样打印它们。如-
#!/usr/bin/perl # This would print with a line break in the middle print "Hello world\n";
这将产生以下输出-
Hello world
您可以在文字字符串周围使用双引号或单引号,如下所示:
#!/usr/bin/perl print "Hello, world\n"; print 'Hello, world\n';
这将产生以下输出-
Hello, world Hello, world\n$
单引号和双引号之间存在重要区别。仅双引号可插值变量和特殊字符(如换行符\n),而单引号不会插值任何变量或特殊字符。
#!/usr/bin/perl $a=10; print "Value of a=$a\n"; print 'Value of a=$a\n';
这将产生以下输出-
Value of a=10 Value of a=$a\n$
下面是一个简单的多行文本语法,请仔细检查<<和标识符之间是否没有空格。
标识符可以是一个简单的单词,也可以是一些引用的文本,如下面我们使用的EOF。
#!/usr/bin/perl $a=10; $var=<<"EOF"; This is the syntax for here document and it will continue until it encounters a EOF in the first line. This is case of double quote so variable value will be interpolated. For example value of a=$a EOF print "$var\n"; $var=<<'EOF'; This is case of single quote so variable value will be interpolated. For example value of a=$a EOF print "$var\n";
这将产生以下输出-
This is the syntax for here document and it will continue until it encounters a EOF in the first line. This is case of double quote so variable value will be interpolated. For example value of a=10 This is case of single quote so variable value will be interpolated. For example value of a=$a
Perl使用反斜杠(\)字符转义可能干扰我们代码的任何类型的字符。让我们举一个示例,我们要打印双引号和$符号-
#!/usr/bin/perl $result="This is\"number\""; print "$result\n"; print "\$result\n";
这将产生以下输出-
This is "number" $result
Perl标识符是用于标识变量,函数,类,模块或其他对象的名称。 Perl变量名称以$,@或%开头,后跟零个或多个字母,下划线和数字(0到9)。
Perl不允许在标识符中使用标点符号,如@,$和%。 Perl是区分大小写的编程语言。 因此,$Manpower和$manpower是Perl中的两个不同的标识符。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)