Perl – 从数组创建哈希
散列是将给定键转换为另一个值的过程。哈希函数用于根据数学算法生成新值(称为哈希)。
Perl 哈希是由键值对定义的。 Perl 以最佳方式存储散列元素,您可以非常快速地根据键查找其值。与标量或数组变量一样,散列变量也有自己的前缀。哈希变量必须以百分号 (%)开头。哈希键必须是唯一的。如果您尝试使用已存在的键添加新的键值对,则现有键的值将被覆盖。
例子:
#!/usr/bin/perl
# defines a hash named subjects
# the first scalar inside the
# brackets are hashes and the
# second one beside them are values
my %subjects = qw(Physics Laws
Chemistry Exceptions
Mathematics Formulas
Programming Fun);
# getting the value of Programming
print($subjects{'Programming'});
输出:
Fun
为了使代码更优雅、更易于阅读,Perl 提供了 =>运算符。它有助于区分键和值。键始终使用 =>运算符指向它们对应的值。但是,这里 Perl 要求哈希的键是字符串,同时值可以是任何标量。如果使用非字符串值作为键,可能会得到意想不到的结果。可以使用 =>运算符重写 $subjects 哈希,如下所示:
#!/usr/bin/perl
# declaring hash using the => operator
my %subjects = ( Physics => 'Laws',
Chemistry => 'Exceptions',
Mathematics => 'Formulas',
Programming => 'Fun' );
# getting the value of Mathematics
print($subjects{'Mathematics'});
输出:
Formulas
哈希分配中的奇数个元素
当散列分配中的元素数是奇数时,Perl 会向我们发出警告,因为它注意到分配给散列的元素数不能除以 2。元素数是奇数。
由于这只是一个警告(并且仅在“使用警告”生效时才显示),脚本将继续分配。奇数元素(“物理”、“化学”、“数学”和“编程”)将成为键,偶数元素(“定律”、“例外”和“公式”)将成为值。因为元素的数量是奇数,所以最后一个键(“Programming”)不会有一对。
#!/usr/bin/perl
use warnings;
use strict;
# declaring hash with odd number
# of assignments
my %subjects = qw( Physics Laws
Chemistry Exceptions
Mathematics Formulas
Programming );
print "Physics = $subjects{'Physics'}\n";
print "Chemistry = $subjects{'Chemistry'}\n";
print "Mathematics = $subjects{'Mathematics'}\n";
print "Programming = $subjects{'Programming'}\n";
输出
Physics = Laws
Chemistry = Exceptions
Mathematics = Formulas
Programming =
Odd number of elements in hash assignment at line 7.
Use of uninitialized value $subjects{"Programming"} in print at line 12.
添加、删除和修改哈希的元素
向 Hash 添加新元素并对其进行修改,彼此非常相似。散列名称后跟用花括号括起来的键并分配一个值。我们可以使用 delete函数来删除一个哈希。以下示例代码显示了如何从哈希中分配/修改和删除元素:
#!/usr/bin/perl
# declaring a hash
my %subjects = ( Physics => 'Laws',
Chemistry => 'Exceptions',
Mathematics => 'Formulas',
Programming => 'Fun' );
# extracting keys of hash in an array
@keys = keys %subjects;
# determining size of keys-array i.e.
# number of elements in hash
$size = @keys;
print "Hash size is $size\n";
# adding an element to the hash;
$subjects{'Biology'} = 'Boring';
# determining size of hash after
# adding an element
@keys = keys %subjects;
$size = @keys;
print "Hash size is $size\n";
# removing an element from hash
delete $subjects{'Chemistry'};
# determining size of hash after
# removing an element
@keys = keys %subjects;
$size = @keys;
print "Hash size is $size\n";
# modifying an element of hash
$subjects{'Mathematics'} = 'Intriguing';
# looping over the hash
for(keys %subjects){
print("$_ is $subjects{$_}\n");
}
输出:
Hash size is 4
Hash size is 5
Hash size is 4
Mathematics is Intriguing
Physics is Laws
Programming is Fun
Biology is Boring