A hash is a collection of key/value pairs.
Hash variables in Perl start with a percent sign (%).
Access hash element format: ${key} .
Here is a simple hash example:
Executing the above program, the output result is:
There are two ways to create a hash:
$data{'google'} = 'google.com';$data{'codercto'} = 'codercto.com';$data{'taobao'} = 'taobao.com';
The first element in the list is key, and the second element is value.
%data = ('google', 'google.com', 'codercto', 'codercto.com', 'taobao', 'taobao.com');
You can also use the => symbol to set key/value:
%data = ('google'=>'google.com', 'codercto'=>'codercto.com', 'taobao'=>'taobao.com');
The following example is a variation of the above example, using - instead of quotes:
%data = (-google=>'google.com', -codercto=>'codercto.com', -taobao=>'taobao.com');
In this way, spaces cannot appear in the key. The way to read elements is:
$val = $data{-google}$val = $data{-codercto}
Access hash element format: ${key} , the example is as follows:
Executing the above program, the output result is:
You can extract values from a hash just like an array.
The hash value is extracted into an array syntax format: @{key1,key2} .
Executing the above program, the output result is:
Array: 45 40
We can use the keys function to read all the keys of the hash. The syntax is as follows:
keys %HASH
This function returns an array of all keys for all hashes.
Executing the above program, the output result is:
taobaogooglecodercto
Similarly, we can use the values function to read all the values of the hash. The syntax format is as follows:
values %HASH
This function returns an array of all values for all hashes.
Executing the above program, the output result is:
taobao.comcodercto.comgoogle.com
If you read a key/value pair that does not exist in the hash, an undefined value will be returned and a warning will appear during execution.
In order to avoid this situation, we can use the exists function to determine whether the key exists and read it when it exists:
Executing the above program, the output result is:
facebook key does not exist
In the above code, we used the IF...ELSE statement, which we will introduce in detail in the following chapters.
The hash size is the number of elements. We can get the hash size by first getting all the element arrays of key or value, and then calculating the number of array elements. The example is as follows:
Executing the above program, the output result is:
1 - Hash size: 32 - Hash size: 3
Adding key/value pairs can be done through simple assignment. But to delete a hash element you need to use the delete function:
Executing the above program, the output result is:
1 - hash size: 32 - hash size: 43 - hash size: 3