Perl Language(III)

本文深入讲解Perl中的哈希数据结构,包括语法、赋值、遍历等操作,并演示了如何使用哈希解决实际问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Perl Language(III)

5. Hash(Key-Value)
5.2 Hash syntax
my %hash;

my %hash;
$hash{key} = 'value';
$hash{name} = "sillycat";
print $hash{key} . " " . $hash{name};

my $var = 1;
my @var = (1,2,3,4);
my %var;
$var{1} = 2;
$var{2} = 38;
print $var . " " . $var[3] . " " . $var{2}

console output:
1 4 38

my %hash;
for (1...5) {
$hash{$_*2} = $_**2;
}

equals to

$hash{2} = 1;
$hash{4} = 4;
$hash{6} = 9;
$hash{8} = 16;
$hash{10} = 25;

5.3 put the value in hash
my %hash = qw/1 one 2 two 3 three/;

equals to

$hash{1} = 'one';
$hash{2} = 'two';
$hash{3} = 'three';

equals to

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

5.4 each
my %hash = (
1 => 'one',
2 => 'two',
3 => 'three',
);

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

console output:
1 = one
3 = three
2 = two

my %hash = (
'168.1.0.1' => 'sillycat',
'192.168.0.2' => 'carl',
'192.168.1.3' => 'luohuazju',
);
my @hostname;
while (my ($key, $value) = each (%hash)) {
if ($key =~ /^192/) {
push @hostname, $value;
}
}

print join ",", @hostname;

console output:
luohuazju,carl

5.5 keys and values
my @keys = keys(%hash);

my @values = values(%hash);

my @keys = keys(%hash);
for (@keys) {
print "$_ => $hash{$_}\n";
}

my %hash = (
'168.1.0.1' => 'sillycat',
'192.168.0.2' => 'carl',
'192.168.1.3' => 'luohuazju',
);

my @keys = map { $hash{$_} }
grep { (m/^192/) } keys(%hash);

print join "," ,@keys;

console output:
luohuazju,carl

5.6 operation of hash
5.6.1 exists
my %hash = (
'168.1.2.1' => 'verdi',
'192.1.2.2' => 'wagner',
'168.1.2.3' => 'beethoven',
);
my $ip = '192.1.2.2';
print "bingo" if ($hash{$ip});

my %hash = (
'cd' => 2,
'book' => 10,
'video' => 0,
);
my $media = 'video';
print "bingo" if ($hash{$media});

equals

print "exist" if (grep { $_ eq 'video' } keys (%hash));

equals

print "exists" if (exists $hash{video});

5.6.2 delete
delete $hash{video};

6. Sub function
my $num = 12;
print hex($num),"\n";
print &hex($num),"\n";

sub hex {
$num*2;
}

&hello;
&hello;
sub hello {
print "hello\n";
}

6.2 Parameters
&hello("sillycat");

sub hello {
print @_;
}

&hello("hello", "sillycat");

sub hello {
my $action = shift @_;
my $name = shift @_;
print "$action $name\n";
}

console output:
hello sillycat

6.3 Return Value

my $return = &times(4);
print $return;

sub times {
my $max = shift;
my $total = 1;
for (1...$max) {
$total *= $_;
}
return $total;
}
console output: 24

6.4 More Parameters
my $return = &div(4, 2);
print $return;

sub div {
$_[0]/$_[1];
}


references:
http://easun.org/perl/perl-toc/
http://perl.apache.org/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值