2012年1月17日 星期二

[Perl 文章收集] Hash 使用範例

前言 : 
雜湊在Perl中是以百分比符號(%)作為表示,變數的命名方式則維持一貫原則,也就是可以包含字母,數字及底線的字串,但是不能以數字作為開頭。所以你可以像這樣的方式定義一個雜湊變數 : 
my %hash; # 基本的命名方式
my %ID_Hash; # 包含底線的變數
my %id_hash; # 大小寫還是被認為是不同的字串
my %_underline; # 以底線開始的變數名稱
my %2hash; # 程式會產生錯誤,因為這不是合法的變數

接著底下要來介紹一些常用的 Hash 操作與對應範例代碼. 

Initialize a hash : 
Assigning an empty list is the fastest way. 
範例代碼 : 
my %hash = ();

Clear (or empty) a hash : 
If you literally want to empty the contents of a hash. 
範例代碼 : 
  1. for (keys %hash)  
  2. {  
  3.         delete $hash{$_};  
  4. }  
Clear (or empty) a hash reference : 
範例代碼 : 
  1. for (keys %$href)  
  2. {  
  3.         delete $href->{$_};  
  4. }  
Add a key/value pair to a hash : 
In the solutions below, quotes around the keys can be omitted when the keys are identifiers. 
範例代碼 : 
  1. $hash{ 'key' } = 'value';    # hash  
  2. $hash{ $key } = $value;      # hash, using variables  
  3. $href->{ 'key' } = 'value';  # hash ref  
  4. $href->{ $key } = $value;    # hash ref, using variables  
Add several key/value pairs to a hash : 
The following statements are equivalent, though the second one is more readable. 
範例代碼 : 
  1. %hash = ( 'key1''value1''key2''value2''key3''value3' ); # First one  
  2. %hash = (  
  3.         key1 => 'value1',  
  4.         key2 => 'value2',  
  5.         key3 => 'value3',  
  6.     ); # Second one  
Copy a hash : 
範例代碼 : 
  1. my %hash_copy = %hash;  # copy a hash  
  2. my $href_copy = $href;  # copy a hash ref  
Delete a single key/value pair : 
The solution differs for a hash and a hash reference, but both cases can use the delete function. 
範例代碼 : 
  1. delete $hash{$key};   
  2. delete $hash_ref->{$key};  
Perform an action on each key/value pair in a hash : 
The actions below print the key/value pairs. 
範例代碼 : 
  1. my %form = ();  
  2. %form = (  
  3.     key1 => 'value1',  
  4.     key2 => 'value2',  
  5.     key3 => 'value3'  
  6.     );  
  7.   
  8. print "Using while loop: \n";  
  9. while(my($key, $value) = each(%form)){  
  10.     print "\t$key => $value\n";  
  11. }  
  12.   
  13. print "Using for loop: \n";  
  14. for my $key (keys %form) {  
  15.     my $value = $form{$key};  
  16.     print "\t$key => $value\n";  
  17. }  
Get the size of a hash : 
範例代碼 : 
  1. my %form = ();  
  2. %form = (  
  3.     key1 => 'value1',  
  4.     key2 => 'value2',  
  5.     key3 => 'value3'  
  6.     );  
  7.   
  8. print "size of hash form (implicit): " . keys(%form) . "\n"; # method1 : implicit scalar context  
  9.   
  10. my $i = 0;  
  11. $i += scalar keys %form; # method2 : explicit scalar context  
  12. print "size of hash form (explicit): " . $i;  
Use hash references : 
範例代碼 : 
  1. sub foo  
  2. {  
  3.     my $hash_ref;  
  4.     $hash_ref->{'key1'} = 'value1';  
  5.     $hash_ref->{'key2'} = 'value2';  
  6.     $hash_ref->{'key3'} = 'value3';  
  7.       
  8.     return $hash_ref;  
  9. }  
  10.   
  11. my $hash_ref = foo();  
  12.   
  13. for my $key (keys %$hash_ref)  
  14. {  
  15.     print "Key=$key ; Value=$hash_ref->{$key}...\n"  
  16. }  
Create a hash of hashes; via references : 
The following two solutions are equivalent, except for the way the look. In my opinion the second approach is clearer. 
範例代碼(1) : 
  1. $patch="test";  
  2. $os = "Win";  
  3. $arch = "86";  
  4. $info = "XP";  
  5. $requiredPatches_href->{$patch}->{os} = $os;  
  6. $requiredPatches_href->{$patch}->{arch}   = $arch;  
  7. $requiredPatches_href->{$patch}->{info}   = $info;  
  8.   
  9. print "requiredPatches_href->$patch->os= " . $requiredPatches_href->{$patch}->{os} . "...\n";  
  10. print "requiredPatches_href->$patch->arch= " . $requiredPatches_href->{$patch}->{arch} . "...\n";  
  11. print "requiredPatches_href->$patch->info= " . $requiredPatches_href->{$patch}->{info} . "...\n";  
範例代碼(2) : 
  1. $requiredPatches_href->{ $patch } = {  
  2.                                           os    => $os,  
  3.                                           arch  => $arch,  
  4.                                           info  => $info,  
  5.                                         };  
Function to build a hash of hashes; return a reference : 
底下範例代碼使用函式 foo 讀取 /etc/passwd 後, 使用 "用戶名" 當 key ; 並將該用戶資訊用 hash 的 hash 存放後返回 hash : 
範例代碼 : 
  1. sub foo  
  2.     {  
  3.         my ( $login, $p, $uid, $gid, $gecos, $dir, $s );  
  4.        
  5.         my %HoH = ();  
  6.        
  7.         my $file = '/etc/passwd';  
  8.         open( PASSWD, "< $file" ) or die "Can't open $file : $!";  
  9.        
  10.         while( ) {  
  11.             ( $login, $p, $uid, $gid, $gecos, $dir, $s ) = split( ':' );  
  12.        
  13.             $HoH{ $login }{ 'uid' } = $uid;  
  14.             $HoH{ $login }{ 'gid' } = $gid;  
  15.             $HoH{ $login }{ 'dir' } = $dir;  
  16.         }  
  17.        
  18.         close PASSWD;  
  19.        
  20.         return \%HoH;  
  21.     }  
Access and print a reference to a hash of hashes : 
範例代碼(1) : 
  1. my $rHoH = foo();       
  2. my( $uid, $gid, $dir );  
  3.        
  4. for my $login ( keys %$rHoH ) {       
  5.         $uid =       $rHoH->{ $login }->{ 'uid' };   # method 1  most readable  
  6.         $gid =    ${ $rHoH->{ $login } }{ 'gid' };   # method 2  
  7.         $dir = ${ ${ $rHoH }{ $login } }{ 'dir' };   # method 3 least readable  
  8.        
  9.         print "uid: $uid, gid: $gid, dir, $dir.\n";  
  10. }  
範例代碼(2) : 
  1. my $rHoH = foo();  
  2.        
  3. for my $k1 ( sort keys %$rHoH ) {  
  4.         print "k1: $k1\n";  
  5.         for my $k2 ( keys %{$rHoH->{ $k1 }} ) {  
  6.             print "k2: $k2 $rHoH->{ $k1 }{ $k2 }\n";  
  7.         }  
  8. }  
Print the keys and values of a hash, given a hash reference : 
範例代碼 : 
  1. while( my ($k, $v) = each %$hash_ref ) {  
  2.         print "key: $k, value: $v.\n";  
  3. }  
Determine whether a hash value exists, is defined, or is true : 
範例代碼 : 
  1. print "Value EXISTS, but may be undefined.\n" if exists  $hash{ $key };  
  2. print "Value is DEFINED, but may be false.\n" if defined $hash{ $key };  
  3. print "Value is TRUE at hash key $key.\n"     if         $hash{ $key };  

補充說明 : 
Perl 學習手扎 - 5. 雜湊(Hash) 
[Perl] Something about hash of Perl 
PERL: How to remove an element from hash or array? 
In order to remove an element from the array or hash, we have to use the delete keyword on perl. Using the delete keyword on the key of the hash or array (numeric keyed hash), we can delete elements of a hash or array.

Perl Hash Howto 
Perl Tutorial - hashes

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...