perlnote4

#!/usr/bin/perl -w



use strict;



=head

this section describe hash;

=cut





=head1

1 define:

  my %[a-zA-Z_]str; the name begin with a-zA-Z_, digit is denied;

  <key, value> pair, NOTE: perl turn key to a string, if key is an expression,

  perl first calculate it and treat its result as the key; 

  e.g. $hash{'4/2'} equals to $hash{2}, but $hash{"4/2"}, "4/2" is recognized

       as a string instead of an expression;

  the value must be the string, e.g. "string"or 'string' types;



2 initialize

  my %hash;

  $hash{key} = 'value';

  print $hash{key};

  my %hash = (1 2 3 4);

  my %hash = qw/key1 value1 key2 value2 key3/; $hash{key3} is undef;

  my %hash = (1 => 'one', 2=>'two');



3 operation

  traversal: while (my ($key, $value) = each (%hash)), get each  pair;

  keys: @keys = keys(%hash); get all keys and store them to an array;

  values: @values = values(%hash);

  exists: exists $hash{key}, return true or false;

  delete: delete $hash{key}; 



4 order of <key, value> in hash

  it is not the same order as <key, value> inserted, perl will perform the most

  optimized order to store in memory; 

=cut



# define

print "define............................./n";

my %hash;

$hash{1} = "one"; print "hash{1}=$hash{1}/n";

$hash{2} = 'two'; print "hash{2}=$hash{2}/n";

$hash{'4/2'} = 'string /'4/2/''; print "hash{/'4/2/'}=$hash{4/2}/n";

$hash{"4/2"} = 'string "4/2"'; print "hash{/"4/2/"}=$hash{/"4/2/"}/n";

%hash = qw//;print keys(%hash);

delete $hash{$_} for keys(%hash); # we can empty a hash in the 2 ways

for (1...3) {

    $hash{$_**2} = $_**2;

}

while (my ($key, $value) = each (%hash)) {print "<$key, $value>/n";}



# get value whose key(ip) begin with 192

%hash = qw//;

%hash = (

	'168.1.2.1' => 'verdi',

	'192.1.2.2' => 'wagner',

	'168.1.2.3' => 'leo',);

while (my ($key, $value) = each (%hash)) {

    print "$hash{$key}/n" if ($key =~ /^192/); # no use of $value

}



grep {} keys($hash)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值