perl哈希的一个实例分析

时间:2023-07-23 21:35:16 


#!/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=();

标签:哈希
0
投稿

猜你喜欢

  • 完美解决Pycharm中matplotlib画图中文乱码问题

    2021-11-01 00:25:35
  • Python3中PyQt5简单实现文件打开及保存

    2023-10-17 21:45:52
  • 选择utf-8还是GB2312?

    2009-06-19 13:05:00
  • Golang中的time.Duration类型用法说明

    2024-05-02 16:24:12
  • Oracle数据库编写有效事务指导方针

    2009-03-19 17:41:00
  • 使用Python对Csv文件操作实例代码

    2023-04-17 23:50:57
  • Python机器学习之实现模糊照片人脸恢复清晰

    2021-02-13 09:56:53
  • SQLserver中的declare变量用法

    2024-01-18 22:40:19
  • SQL Server数据在不同数据库中的应用

    2008-12-24 15:34:00
  • 浅谈Python描述数据结构之KMP篇

    2022-06-09 19:36:23
  • python获取糗百图片代码实例

    2022-09-10 01:44:01
  • 远程访问MySQL数据库的方法小结

    2024-01-13 17:58:57
  • python 读取目录下csv文件并绘制曲线v111的方法

    2022-08-21 16:05:34
  • 10个Python小技巧你值得拥有

    2022-02-03 16:28:56
  • ASP获取网址或当前地址代码

    2008-04-07 20:19:00
  • django框架中ajax的使用及避开CSRF 验证的方式详解

    2023-05-11 02:10:41
  • Python操作列表的常用方法分享

    2021-06-02 12:41:29
  • PyChon中关于Jekins的详细安装(推荐)

    2021-03-17 08:07:31
  • Python在cmd上打印彩色文字实现过程详解

    2022-12-19 07:27:33
  • 简单理解vue中track-by属性

    2024-04-30 10:21:05
  • asp之家 网络编程 m.aspxhome.com