以下是依据perlintro总结的Perl基本语法
-
Perl 语法-- by gouven
-
数据类型see perldata
-
scalar
-
分类
-
字符串
-
(双引号支持变量解析及特殊字符如n):"abc",'abc';
-
支持“乘法”表示:'a' x 3 等同于'aaa';
-
引用(reference)see perlreftut,perlref
-
array
-
@array 在scalar上下文中表示数组元素个数,如 if(@array < 10) {}
-
数组元素使用使用$+数组下标(从0开始)进行引用,如$name[0]
-
hash
-
初始化
-
%table = (1,'one','two');
-
%table = ( 1 => 'one',2 => 'two',);
-
获取所有的value: values @table
-
变量作用域
-
my声明到作用域在{}内,如if() {my $foo = 1;}
-
分支 & 循环see perlsyn
-
if
-
if(cont){} elsif(cont2) {} else {} #必须有{}
-
while
-
print 'foo' while its_true;
-
until
-
print 'foo' until its_false;
-
for
-
for($i = 0; i < 10; $i++) {}
-
foreach
-
foreach (@array) {print $_;} #实际是foreach $iter (@array) {print $iter;}
-
print "$_n" foreach 1 .. $max; #每次获取到放在$_,不支持放到其他变量中
-
foreach my $key (keys %table) {print "$key : ${$key}n";}
-
总结
-
关键字在前的,需要把条件放在()中;关键字在后到,不需要{}
-
函数sub
-
sub your_sub_name { my (arg1,arg2) = @_; return $retval;}
-
文件操作
-
打开
-
open(my $in,'<','file.txt'); # to readopen my $in,'<file.txt'; #another way
-
open(my $out,'>','file.txt'); # to read
-
open(my $append,'>>','file.txt'); # to append
-
读
-
my $line = <$in>; # scalar context
-
my @all_lines = <$in>; # list context
-
while(<$in>) {print "line: $_n";}
-
写: print $out,"feed some text";
-
关闭: close $in; close $out;
-
regex
-
判断匹配
-
if(/foo/) {} # if $_ contains 'foo'
-
if($bar =~ /foo/) {} # if $bar contains 'foo'
-
简单的字符串替换
-
s/foo/bar; # replace foo with bar in $_;
-
$line =~ s/foo/bar; # replace foo with bar in $line;
-
more details in perlrequick,perlretut,perlre
-
模块
-
MyModule.pm #文件名以大写开头,扩展名一般为pm
-
MyModule.pm内容
-
see http://perlmonks.org/?node_id=102347
-
perl -V #查看当前perl配置,包括@INC数组
-
perl -I/path/to/module/testd xxx.pl #临时添加模块目录到@INC
Perl 语法-- by gouven//mm2html.xsl FreeplaneVersion:freeplane 1.3.0
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|