Basic usage
# Initialize % h as an empty array % h = {};
# Use an array to initialize % h as a => 1, B => 2% h = ('A', 1, 'B', 2 );
# The meaning is the same as above. It is just a more Visualized Method. % H = ('A' => 1, 'B' => 2 );
# If the key is a string, quotation marks can be omitted. 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 a key using delete $ h {B}; # delete 'B' from $ h'
Clear Perl Hash
Undef % h;
Obtain all hash key values.
# Obtain all keys. The order depends on the hash function, or @ all_keys = keys % h; # all key values are sorted in descending order of hash values. The comparison of values is numerical comparison (for example, 10> 9), @ all_keys = sort {$ h {$ B }=>$ h {$ a} (keys % h );
Determine whether Perl Hash contains a key
Exists ($ h {$ key });
Perl Hash Length
Want to know how much data a hash stores
$ Hash_size = keys % h # Put % h in $ hash_size to print scalar keys % h, "\ n"; # print the length of % h. Scalar is used to return the array length.
Traverse a Perl Hash
While (my ($ k, $ v) = each % h) {print "$ k ---> $ v \ n ";}
Reference
Reference is similar to a C/C ++ pointer.
$ H_ref =\% h; # Get a hash reference, % aHash =%{ $ h_ref }; # Use the hash reference as a hash using $ value = $ h_ref-> {akey}; # This is the same as % h {akey }.
Pass Perl Hash to function
Generally, a reference is passed to the function.
% H = (); $ h {a} = 1; foo (\ % h); print $ h {B}, "\ n"; # print 2. This value comes from the function foo (), sub foo {my ($ h) =@_; print $ h-> {a}, "\ n "; # print out 1 $ h-> {B} = 2 ;}
The function returns a hash or a hash reference)
Functions can return Perl Hash
Sub foo {my % fh; $ fh {a} = 1; return % h;} my % h = foo (); print "$ h {a} \ n "; # print 1
However, this means that the entire hash is copied from % fh to % h, which is less efficient. You can consider returning a hash reference:
Sub foo {my % fh; $ fh {a} = 1; return \ % fh;} my $ hr = foo (); print "$ hr-> {a} \ n"; # print 1. my % h = % {foo ()} # If you want to copy the file, you can also use this method. Do not worry that % fh in sub foo is a local variable. Perl automatically manages the memory. It will find that % fh is referenced by $ hr, and the memory of % fh will not be cleared, and the memory will be released after $ hr becomes invalid.