#!/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)
perlnote4
最新推荐文章于 2024-08-08 13:28:00 发布