以下是依據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', 2, '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