Basic usage
#Initialize% h as an empty array% h = ();
#Initialize% h with array a => 1, b => 2% h = ('a', 1, 'b', 2);
The meaning is the same as above, just another more visual way of writing. % h = ('a' => 1, 'b' => 2);
#If key is a string, you can omit the quotes. The following line is the same as the above line% h = (a => 1, b => 2);
#Use {} to access print "$ h {a} \ n";
#Print $ h {b} = '2b'; print "$ h {b} \ n"; #print 2b
#Delete key with delete delete $ h (b); #Delete 'b' from $ h
Clear Perl Hash
undef% h;
Get all the keys of the hash
#Get all keys, the order depends on the hash function, or in other words @ all_keys = keys% h; The comparison of values is a numerical comparison (for example, 10> 9), @ all_keys = sort {$ h {$ b} => $ h {$ a}} (keys% h);
Determine if Perl Hash contains key
exists ($ h {$ key});
Perl hash length
Want to know how much data a hash stores
$ hash_size = keys% h #put the length of% h into $ hash_size print scalar keys% h, "\ n"; #print the length of% h. Here scalar is used to return the length of the array.
Traversing a Perl Hash
while (my ($ k, $ v) = each% h) {print "$ k ---> $ v \ n";}
Reference
Reference is similar to C / C ++ pointer
$ h_ref = \% h; #Get a hash reference,% aHash =% ($ h_ref}; #Use hash reference as hash $ value = $ h_ref-> {akey}; #this and% h {akey} is the same
Passing Perl Hash to a function
Usually pass a reference to a function
% h = (); $ h {a} = 1; foo (\% h); print $ h {b}, "\ n"; #Print out 2. This value comes from the function foo (), sub foo {my ($ h) = @ _; print $ h-> {a}, "\ n"; #print out 1 $ h-> {b} = 2;}
Function returns hash, or hash reference
Functions can return Perl Hash
sub foo {my% fh; $ fh {a} = 1; return% h;} my% h = foo (); print "$ h {a} \ n"; #print out 1
But this is equivalent to copying the entire hash from% fh to% h, which is relatively inefficient. Consider returning a reference to the hash:
sub foo {my% fh; $ fh {a} = 1; return \% fh;} my $ hr = foo (); print "$ hr-> {a} \ n"; #Print out 1. my% h =% {foo ()} #If you just want to copy, you can also use this method. Don't worry that% fh in sub foo is a local variable, Perl will automatically manage memory. It will find that% fh is referenced by $ hr, it will not clean up the memory of% fh, and release the memory after $ hr expires.