Perl 的參考和 C 的指標差不多, {$p} 相當於 C 的 *p 取出指標指向的變數, ${$p}{key} 寫起來太麻煩, 可改用 $p->{key} 比較好寫, 這點也和 C 的 -> 同樣。取參考用 \ 類似 C 的 &, 像是 \%h 和 \@a 各別是取出雜湊 %h 和陣列 @a 的參考。另外要注意的是 Perl 會看 @、% 決定變數的意義, 等號左邊用什麼符號, 就決定它的語境。
另外 Perl 有 GC 的機制, 不用擔心從函式內傳回參考後, 資料會不見。
陣列和參考
@a = qw/x y z/; print @a, "\n"; # xyz # reference of an array $p = \@a; print $p, "\n"; # ARRAY(0x605050) print "\$p[0]: ", $p[0], "\n"; # $p[0]: print "\${\$p}[0]: ", ${$p}[0], "\n"; # ${$p}[0]: x print "\$p->[0]: ", $p->[0], "\n"; # $p->[0]: x unshift @{$p}, "w"; print @{$p}, "\n"; # wxyz # [] $p = []; print "\$p: ", $p, "\n"; # $p: ARRAY(0x6326a0) push @{$p}, "q"; print ${$p}[0], "\n"; # q print $p->[0], "\n"; # q $p2 = []; print "\$p2: ", $p2, "\n"; # $p2: ARRAY(0x6326c0) # subroutine sub foo { $pp = shift; print @{$pp}, "\n"; # wxyz } foo(\@a);
雜湊和參考
# two ways to initialize a hash. %h = qw(k1 v1 k2 v2); print %h, "\n"; # k2v2k1v1 print $h{k1}, "\n"; # v1 %h2 = ( k1 => 'v1', k2 => 'v2', ); print "--------------\n"; print %h2, "\n"; # k2v2k1v1 print $h2{k1}, "\n"; # v1 # {} generates a reference of hash. $h3 = { k1 => 'v1', k2 => 'v1', }; print "--------------\n"; print $h3, "\n"; # HASH(0x6327c0) print %{$h3}, "\n"; # k2v2k1v1 print $h3->{k1}, "\n"; # v1 # subroutine. sub foo { $p = shift; print "--------------\n"; print $p, "\n"; print %{$p}, "\n"; } # get the reference of %h. foo(\%h); # HASH(0x605050) # k2v2k1v1 # #h3 is already a reference. foo($h3); # HASH(0x6327c0) # k2v2k1v1
沒有留言:
張貼留言