perl 哈希(hash)学习笔记(一)

原文地址为: 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

 

 

转载请注明出处

     

  


转载请注明本文地址: perl 哈希(hash)学习笔记(一)
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值