橫軸 Tab 選單

2010/6/9

[Perl] Something about hash of Perl

最近剛好寫到一些Perl hash的使用,所以把一些相關hash的簡單應用寫出來。

§ 宣告hash (Declare the hash)

my %hash = (
1 => 'one',
2 => 'two',
3 => 'three',
);
or
my %hash = (1, 'one', 2, 'two', 3, 'three');

§ 刪除key/value (Remove one key/value from hash)

delete $hash{1};

§ hash大小 (Size of hash)

my $size_of_hash = keys( %hash );

§ 確認key/value是否存在 (Check key/value exists or not)

print "the key/value exists\n" if exist $hash{$key};

§ 合併hash (Merge two hash into one)

%newhash = (%hash1, %hash2);
@hash1(keys %hash2) = values %hash2;

§ 印出hash中的所有key/value (Print out the keys and values in a hash)

print “$key => $value\n” while(($key, $value) = each %hash);
print “$_ => $hash{$_}\n” for (keys %hash);

§ 按key值排列 (Sorting with the key)

print "$key: $hash{$key}" foreach $key (sort keys %hash); 

§ 按值排列 (Sorting with the value)

print "$value $hash{$value}" foreach $value (sort {$hash{$a} cmp $hash{$b} }  keys %hash) 

沒有留言:

張貼留言