perl 哈希(hash)學習筆記(一)


1.什么是哈希

  哈希是perl的一種數據類型,比較類似數組,用於存放數據,包括2部分關鍵字keys和值value。不同於數組,哈希訪問元素的是按照名字訪問標量的key=>value.

hash 用% 來標示

2.hash 操作

   a.增加

     my %hash; //定義

  第一種寫法:$hash{'author'}="Young";  #author 是關鍵字,Young 是value     與數組一樣,hash作為整體時候是這樣%hash 帶標示符%,作為單個元素使用要使用$而不是%

     第二種寫法: my %food=('fruit',"apple",'drink',"Coco");         #類似數組初始化 注意這里使用的是( )不是{}  {},用了它實際就是創建了一個引用,正確的就是(),圓括號否則會報 Reference found where even-sized list expected at hash.pl line 4.

   第三種寫法:my %fruit=(apple=>"fruit",banana=>'fruit');    #     =>是perl運算符,用於hash    

   b.使用hash值

       單個使用:$hash{'author'};         #       $哈希名{$keyword}

       全部使用:foreach $key (keys %food) 

                      {   

                                  print  print "$key=>$food{$key}\n";     #使用keys %food 遍歷%food的每一個關鍵字

                           }      

       獲取所有的key:my  @key=keys %fruit;

       獲取所有的value:  my @value=values  %fruit;                                           

3.hash 函數 exists 和delete

   判斷 某個關鍵字是否存在 exists $hash{'auther'}

   刪除某個關鍵字 delete %hash{$keyword}

   刪除整個hash %hash=();

 

 

實例

#!/usr/bin/perl -w
my %hash;
$hash{'author'}="Young";
my %food=('fruit',"apple",'drink',"Coco");
my %fruit=(apple=>"fruit",banana=>'fruit');
print "$hash{'author'}\n";
foreach $key (keys %food)
{
        print "$key=>$food{$key}\n";
}
my  @key=keys %fruit;
my @value=values %fruit;
print @key;
print @value;
print "\n";
print "auther is exists\n" if(exists $hash{'auther'});
delete $food{'drink'};
print "after delete some keyword print \%food\n";
while((my $key,my $value)=each%food)
{
        print "$key=>$value\n";
} 

 

 

結果:

/home/Young> perl hash.pl  
Young
fruit=>apple
drink=>Coco
bananaapplefruitfruit
after delete some keyword print %food
fruit=>apple

 

 

轉載請注明出處

     

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM