使用简单的赋值运算符,只需一行代码即可在Perl哈希中添加新的键/值对。但是要从哈希中删除元素,您需要使用delete函数,如下面的示例所示-
#!/usr/bin/perl %data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40); @keys = keys %data; $size = @keys; print "1 - Hash size: is $size\n"; # adding an element to the hash; $data{'Ali'} = 55; @keys = keys %data; $size = @keys; print "2 - Hash size: is $size\n"; # delete the same element from the hash; delete $data{'Ali'}; @keys = keys %data; $size = @keys; print "3 - Hash size: is $size\n";
输出结果
这将产生以下结果-
1 - Hash size: is 3 2 - Hash size: is 4 3 - Hash size: is 3