標籤:blog 返回 lis number for shift imp div line
【轉載】出處:http://www.cnblogs.com/visayafan/
- 1 數組與引用
- 2 聲明的區別
- 3 訪問的區別
- 4 添加行元素
- 5 添加列元素
- 6 訪問與列印
- 6.1 運算子優先順序
- 6.2 訪問一個
- 6.3 遍曆
- 7 切片
1 數組與引用
此處引用相當於C中的指標。
二維數組第一列不儲存具體元素而是儲存指向該行一維數組的引用。
2 聲明的區別
my @AoA = ( [ "fred", "barney", "pebbles", "bambam", "dino", ], [ "george", "jane", "elroy", "judy", ], [ "homer", "bart", "marge", "maggie", ], );
$ref_to_AoA = [ [ "fred", "barney", "pebbles", "bambam", "dino", ], [ "george", "jane", "elroy", "judy", ], [ "homer", "bart", "marge", "maggie", ], ];
3 訪問的區別
$AoA[$i][$j]
因為第一列數組裡面存放的是引用,所以還可以這樣訪問:
$AoA[$i]->[$j]
$ref_AoA->[$i][$j]
同理引用還可以這樣訪問:
$ref_AoA->[$i]->[$j]
4 添加行元素
my (@AoA, $ref_to_AoA);sub print_AoA{ for (@AoA) { print "@{$_}\n"; } print "\n";}# assign to our array, an array of array references@AoA = ( [ "fred", "barney", "pebbles", "bambam", "dino", ], [ "george", "jane", "elroy", "judy", ], [ "homer", "bart", "marge", "maggie", ], );say $AoA[2][1];$ref_to_AoA = [ [ "fred", "barney", "pebbles", "bambam", "dino", ], [ "george", "jane", "elroy", "judy", ], [ "homer", "bart", "marge", "maggie", ], ];print_AoA();my @tmp = (1, 2, 3, 4);push @AoA, [@tmp]; # 因為數組AoA第一列需要的是引用,而@tmp是數組,直接賦值會出錯。[]表示返回@tmp的引用,即把@tmp的引用push到@AoA最後一行,二維數組行數加1.print_AoA();push @AoA, @tmp;print_AoA();
覆蓋行
#$AoA[0] = @tmp; #$AoA[0]是scalar型,而@tmp是list型,所以用預設把tmp的個數賦給$AoA[0],即$AoA[0]=4;$AoA[0] = [@tmp]; #overwirteprint_AoA();
5 添加列元素
push @{$AoA[0]}, "wilma", "betty";
省略@{}
use v5.14; # needed for implicit deref of array refs by array opspush $AoA[0], "wilma", "betty"; # 在5.14版本之前不能通過,因為以前規定push的第一參數必須為數組。在新版本中當$AoA[0]中存在引用時可以通過,但無引用時不正確。print_AoA();my $aref = undef;#push $aref, qw/some value/; # 出錯:Not an ARRAY referencemy $aref = [@tmp];push $aref, qw/some value/; # 正確,因為aref此時不是個Null 參考print "$aref : @$aref\n";
6 訪問與列印 6.1 運算子優先順序
[email protected]*%&
6.2 訪問一個
print $AoA[$i][$j];print ref_$AoA->[$i]->[$j];
6.3 遍曆
for $aref ( @AoA ) # $aref只是第一列裡面的引用,要想訪問整行必須加@,又$存取層級比@高,所以()可以省略。{ say "\t [ @$aref ],";}
for my $i (0 .. $#AoA){ say "elt $i is @{$AoA[$i]}";}
for my $i (0 .. $#AoA){ for my $j (0 .. $#{$AoA[$i]}){ say "elt $i, $j is $AoA[$i][$j]\n"; }}
7 切片
要訪問幾行幾列元素。和Matlab中訪問矩陣的方法差不多。
my @part = ();my $x = 4;for (my $y = 1; $y<4; $y++){ push @part, $AoA[$x][$y];}# 簡單寫法@part = @{$AoA[4]}[1..4];
my @newAoA = ();for (my $startx= my $i = 1; $i<=5; $i++){ for(my $starty = my $j = 2; $j<=4; $j++){ $newAoA[$i - $startx][$j - $starty] = $AoA[$i][$j]; }}#一個迴圈簡單寫法for (my $x = 1; $x<=5; $x++){ push @newAoA, [@{$AoA[i]}[2 .. 4]];}
sub splice_2D{ my $lrr = shift; my($x_l, $x_h, $y_l, $y_h) = @_; return map( [ @{$lrr -> [$_]} {$y_l .. $y_h}] )$x_l .. $x_h;}@newAoA = splice_2D(\@AoA, 1=>5, 2=>4);
Author: visaya fan <visayafan[AT]gmail.com or visayafan[AT]163.com>
Date: 2011-10-29 15:00:34
HTML generated by org-mode 6.33x in emacs 23
perl二維數組