在 Perl 哈希中添加和删除元素
使用简单的赋值运算符只需一行代码即可在 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
广告