Learning Perl 7

 1. 數組的長度

$#arrayname返回數組最後一個長度的下標。( 默認數組是從0下標開始)
2. 數組的切片Array slicing
從一個數組給另一個數組的元素賦值時,得出的數組稱爲數組片。如果右邊的數組大於左邊的數組時,未使用的值將放棄。如果小於,多出的左邊的值將爲undef。
例如:
@name = ('A','B','C');
@pal = @name[0,1];          #important! array slicing, using @name[...] instead of $name[...]
print @pal."@pal\n";
($pal[2], $pal[3]) = @name[2, 1];
print @pal."@pal\n";
令:
@part = ();
$x = 4;
for ($y = 7; $y < 13; $y++) {
push @part, $AoA[$x][$y];
}
這個循環其實可以用一個切片操作來代替:
 @part = @{ $AoA[4] } [ 7..12 ];
3. 二維數組
第一個下標代表行,第二個代表列。行是未命名的列表,即匿名列表。->運算符,又稱中綴運算符可以用來獲得數組的單個元素。
@matrix = (
    [1, 2, 3],
    [4, 5, 6],
    [],
    []
);
 
print $matrix[0][1], $matrix[1]->[1]."\n";    #寫法作用相同
$matrix[2][2]=<STDIN>;
print $matrix[2]->[2]."\n";
my $i = scalar @{$matrix[0]};
一個指向數組的引用:
 # 一個指向“包含有數組引用的數組”的引用
        $ref_to_AoA = [
            [ "fred", "barney", "pebbles", "bambam", "dino", ],
            [ "homer", "bart", "marge", "maggie", ],
            [ "george", "jane", "elroy", "judy", ],
        ];
        print $ref_to_AoA->[2][2];
與C語言不同,perl中不能隨意變換數組和引用。所以訪問方式不一樣!
讓我們試着從一個文件中讀取二維數組。首先我們演示如何一次性添加一行。首先我們假設有這樣一個文本文件:每一行代表了二維數組的行,而每一個單詞代表了二維數組的一個元素。下面的代碼可以把它們儲存到 @AoA: 
while (<>) {
@tmp = split;
push @AoA, [ @tmp ];
}
當然,你也可以不要臨時變量:
while (<>) {push @AoA, [ split ];}
如果你知道想要放在什麼地方的話,你也可以不要 push(),而是直接進行賦值:
my (@AoA, $i, $line);
for $i ( 0 .. 10 ) {
$line = <>;
$AoA[$i] = [ split ' ', $line ];
}
你可能生怕 <> 在列表上下文會出差錯,所以想要明確地聲明要在標量上下文中對 <> 求值,這樣可讀性會更好一些: (譯者注:列表上下文中,<>返回所有的行,標量上下文中 <> 只返回一行。)
my (@AoA, $i);
for $i ( 0 .. 10 ) {
$AoA[$i] = [ split ' ', scalar(<>) ];
      }
如果你想用 $ref_to_AoA 這樣的一個引用來代替數組,那你就得這麼寫:
      while (<>) {
         push @$ref_to_AoA, [ split ];
}
打印整個數組:不支持對引用的自動展開print運算。需要以此迭代輸出:
for $aref ( @AoA ) {
            print "\t [ @$aref ],\n";
}
或者
for $i ( 0 .. $#AoA ) {
            print "\t elt $i is [ @{$AoA[$i]} ],\n";
}
二重循環輸出:
for $i ( 0 .. $#AoA ) {
            $aref = $AoA[$i];
            for $j ( 0 .. $#{$aref} ) {
                print "elt $i $j is $AoA[$i][$j]\n";
            }
        }
    哦,好像還有點複雜,那麼試試這樣:
       for $i ( 0 .. $#AoA ) {
            $aref = $AoA[$i];
            $n = @$aref - 1;
            for $j ( 0 .. $n ) {
                print "elt $i $j is $AoA[$i][$j]\n";
            }
        }
 
4. 散列的分片
@info = qw(Marine Captain 50000);
@officer{‘BRANCH’, ‘TITLE’, ‘SALARY’} = @info;
散列的散列
anonymous hashs in a hash
%students=(Math => {Joe => 100, Joan => 95}, Science => {Bill => 85}, Dan => 76);
獲得散列中的匿名散列的元素
$students{Math}->{Joan}
獲得整個匿名散列
%{$students{Math}}
anonymous arrays in a hash
%grades=(
Math => [89,90],
English => [79,69]
);
$grades{Math}[1];
$grades{Math}->[1];
 
@{$grades{English}} the anonymous array
散列的數組
@stores=(
{Boss=>”Ari Goldberg”,
Registers=>10
},
{Boss=>”Amy Goldberg”,
Registers=>5
});
the numbers of element in the array is $#array+1
for($i=0; $i<$#sores+1; $i++){
print $stores[$i]->{“Boss”};
print ‘___’ x 20, “\n”
}
5. 輸入函數
(1). <STDIN>
列表上下文下,每一行將作爲列表中的一項。使用EOF結束(UNIX ctrl+D)
@all=<STDIN>
(2).read函數
read函數用於從規定的文件句柄將字節數讀到變量中。返回讀取到得字節數。如果從標準輸入讀取,文件句柄爲STDIN。
$number = read(STDIN, $favorite, 10);
# if the input string less than 10 chars, press ctrl + D to end.
print "\$number is $number\n, \$favorite is $favorite\n";
(3).getc
從鍵盤或文件獲得單個字符,遇到EOF則返回空字符。
$answer=getc;
 
6. 數組函數
(1). exist $ARRAY[index];
print “Hello, $arr[1]” if exist $arr[1];
print “out of range” if not exist $arr[n];
(2).grep函數對於數組LIST的每個元素都需要求出表達式EXPR的值,返回值是標量(表達式爲真的個數)或者另一個數組(使表達式爲真的元素)。
grep(EXPR, LIST);
@list=(tomatoes, tomorrow, now);
$count=grep(/tom/, list); #count = 2
@rlist=grep(/tom/, list); #rlist = tomatoes, tomorrow
(3).join 與split相反。join(“:”, $hour, $min, $second);
(4).map函數 map EXPR, LIST
@list=(0x64, 0x65, 0x6e);
@words=map chr, @list; #den
@n=(1, 2, 3);
@n=map $_*2+6, @n;
print @n; #8, 10, 12
(5). map {BLOCK} LIST
塊格式,一般配合split函數。生成列表,使得字段成爲數組的元素。
open(PSWD, “/etc/passwd”);
@lines=<PSWD>;
@fields=map {split(“:”)} @lines
foreach $field (@fields) {
print $field.”\n”;
}
 
參考
《Perl by example》
 Perl 二維數組     http://bbs.chinaunix.net/viewthread.php?tid=770848
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章