perl雜湊的一個執行個體分析_perl

來源:互聯網
上載者:User

複製代碼 代碼如下:

#!/bin/perl
use strict; 
use warnings; 

my %movies; 
my $film; 
my %reverse_result; 
my $director; 
my @data; 

%movies = 

  'The Shining'       => 'Kubrick', 
  'Ten Commandments'  => 'DeMille', 
  'Goonies'           => 'Spielberg', 
); 

#輸出雜湊的值,輸出的結果為Kubrick 
print $movies{'The Shining'}; 

#同時輸出鍵和值 
foreach $film(keys %movies) 

   print "$film was directed by $movies{$film}.\n"; 


#添加空格 
print "\n"; 

#雜湊結構的切換 
%reverse_result=reverse %movies; 
foreach $director(keys %reverse_result) 

   print "$director directe the $reverse_result{$director}.\n";  
}

#添加空格 
print "\n";

#當雜湊結構用於列表環境中時,perl會將hash重新變為由關鍵詞和索引值組成的普通列表 
@data=%movies; 
 print "@data\n"; 

#添加空格 
print"\n"; 

#得到的數組是一個分為奇數為film,偶數為director的數組,或者相反 
#然後我們將數組賦值給hash 
%movies=@data; 
foreach $director(keys %reverse_result) 

  print "$director directe the $reverse_result{$director}.\n";  
}     
print "The result is not change\n";

以下為輸出結果:
    F:\>perl\a.pl 
    KubrickGoonies was directed by Spielberg. 
    The Shining was directed by Kubrick. 
    Ten Commandments was directed by DeMille. 

    DeMille directe the Ten Commandments. 
    Spielberg directe the Goonies. 
    Kubrick directe the The Shining. 

    Goonies Spielberg The Shining Kubrick Ten Commandments DeMille 

    DeMille directe the Ten Commandments. 
    Spielberg directe the Goonies. 
    Kubrick directe the The Shining. 

    F:\>

#----測試雜湊key的方法:
if(exists $hash{keyval}) 


#----刪除關鍵字:
delete hash {keyval};

#---清空雜湊:
%hash=();

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.