Perl Tips

引用

以下从 perldoc perlreftut 得到

语法

创建一个引用

- make rule 1 :

在一个变量前面加 ``/'' 可以得到 对于这个变量的引用.

$aref = \@array;         # $aref now holds a reference to @array
$href = \%hash;          # $href now holds a reference to %hash

如果一个变量的值是另各一个变量的引用,就可以像 scalar 的变量一样使用它.

- make rule 2 :

使用 ``['' 和 ``]'' 可以创建对一个数组匿名引用. 使用``{'' 和 ``} '' 可以创建一个 hash 的匿名引用.

$aref = [ 1, "foo", undef, 13 ];
# $aref now holds a reference to an array
$href = { APR => 4, AUG => 8 };
#$href now holds a reference to a hash

使用引用

- use rule 1:

如果 $aref 是一个数组引用,那么任何可以出现数 组符号 @ 后面的名字 array ,都可以用 @{$aref} 代替 @array.

@a              @{$aref}                An array
reverse @a      reverse @{$aref}        Reverse the array
$a[3]           ${$aref}[3]             An element of the array
$a[3] = 17;     ${$aref}[3] = 17        Assigning an element

对于 hash 的引用类似.

%h              %{$href}              A hash
keys %h         keys %{$href}         Get the keys from the hash
$h{'red'}       ${$href}{'red'}       An element of the hash
$h{'red'} = 17  ${$href}{'red'} = 17  Assigning an element

- use rule 2:

用`` $aref->[3&#93 '' 代替`` ${$aref}->[3&#93 '' , 用`` $href->[red&#93 '' 代替`` ${$href}->[red&#93 '' ,

- arrow rule:

什么时候可以省略`` -> '' . 两个连续的下标之间可以省略 `` -> '' . 用 `` $a[1][2] '' 代替 `` $a[0]->[1] '' .

- 其他 (非常重要)

  1. 你可以建立任何变量的引用,包括函数.
  2. 在 make rule 1 中, 如果最里面的引用是一个 atomic scalar 变量,那么就可以省略花括弧
  3. 可以用 ref 函数测试一个变量是否是一个引用变量.
  4. 字符串变量可以像引用一样的使用.

类似 BASH 的 cat 的功能

看来只有用 open 语句了

字符串

连接字符串用 ``. '' ,不能用 ``+'' .

正则表达式

比较正则表达式的操作符是 ``~'' , 不匹配的操作符是 ``!~'' . 替换

<pre class"src"> $x="abcde"; $x=~s/abcde/c/;

数组

插入 push

perl -e '@a=(); push @a,1 ; print @a , "\n";'

HASH

while (($key, $value) = each %hash) {
     print $key, "\n";
     delete $hash{$key};   # This is safe
}

Here document

sub here_one () {
   my $weather = "sunny";
   print $OUT <<"EOStr";
Oh great.  It
    is $weather today.
EOStr
}

得到系统变量

$ENV{HOME}