Introduction to the creation and reference of Perl hashes _perl

Source: Internet
Author: User
Tags anonymous arrays data structures hash scalar

There are only two ways to create ' references ', and they are two.

Creating references

Create Rule 1
If you add a '/' number in front of a variable, you get a ' reference ' to the variable.

$aref =/@array; # $aref Keep a ' reference ' to @array
$href =/%hash; # $href Keep a ' reference ' to%hash
When you keep a ' reference ' in a variable like $aref or $href, you can copy or save it like any other scalar.

$xy = $aref; # $xy Now save a ' reference ' to @array
$p [3] = $href; # $p [3] now saves a ' reference ' to%hash
$z = $p [3]; # $z Now save a ' reference ' to%hash
These examples show how to create a ' reference ' to a named variable, but sometimes we create an array or hash without a name. This is similar to the string ' n ' or number ' 80 ' that you use without putting it in a variable.

Create Rule 2

[ITEMS] Creates a new, anonymous array and returns a ' reference ' to the array. {ITEMS} Creates a new, anonymous hash and returns a ' reference ' to that hash.

$aref = [1, "foo", undef, 13];
# $aref Save the ' reference ' for this array
$href = {APR =>; 4, AUG =>; 8};
# $href Save the ' reference ' for this hash
The ' reference ' obtained from Rule 2 and the ' reference ' obtained from Rule 1 are of the same type:

$aref = [1, 2, 3];
# like the above:
@array = (1, 2, 3);
$aref =/@array;
The previous method is the abbreviation for the next two lines, except that the first method does not create an extra array variable @array.

If you just write the symbol [], you will get a new, empty anonymous array. If you use the symbol {}, you can get a new, empty anonymous hash.

Using references

When you create a ' quote ', what can you do with it? It is a scalar, and one can save and retrieve it like any scalar. In addition, there are two ways to use it:

Using Rule 1
You can always replace the name of an array with an array ' reference ' with braces. For example, use the @{$aref} instead of the @array.

Here is a few examples of usage:


@a @{$aref} An array
Reverse @a reverse @{$aref} to sort an array in reverse order
$a a member of the [3] ${$aref}[3] Array
$a [3] = 17; ${$aref}[3] = 17 assigning values to a member
In each row above, two expressions implement the same functionality. On the left is an array of @a operations, and the right-hand one is the operation of the arrays pointed to ' reference ' $aref. They have the same effect on the array.

Use the ' reference ' of the hash and the ' reference ' of the array to be exactly the same.

%h%{$href} a hash
Keys%h keys%{$href} remove keys from hash
$h {' Red '} ${$href} {' Red '} One of the members of the hash
$h {' red '} = ${$href} {' Red '} = 17 assign to a member
You have a ' quote ' no matter what you want to do, using rule 1 already tells you what to do. You just write Perl code like a regular array or hash, and then replace the array or hash name with {$reference}. How do I traverse an entire array when I have only one ' reference '? ' You write like this:

For my $element (@array) {
Then replace the array name @array with ' reference ':

For my $element (@{$aref}) {
' How do I print a hash when I have only one ' reference '? ' First write a code that prints the entire hash:

For my $key (keys%hash) {
Print "$key =>; $hash {$key}/n ";
Then use ' reference ' instead of the name of the hash:

For my $key (keys%{$href}) {
Print "$key =>; ${$href} {$key}/n ";

Using Rule 2

Using Rule 1 is what you really need because it tells you how to handle a ' reference ' and it works for almost any ' reference '. But what we usually do is relate to an array or a member of the group, and using Rule 1 is a cumbersome method, so there's a simple way.

${$aref}[3] too difficult to read, so we write $aref->[3].

${$href}{red} is too cumbersome to write, so we write $href->{red}.

If $aref save an array of ' references ', then $aref->[3] is the fourth member of the array. Instead of confusing $aref [3], this represents a fourth member of a completely different array, the @aref array. Variable $aref and @aref are completely unrelated, just like $item and @item.

Similarly, $href->{' Red ' is part of the variable $href of the hash ' reference ', even if it is a hash without a name. and $href{' Red ' is part of another easily confusing named hash%href. It's easy to forget to write the symbol '-> ', and if this happens, when your program takes a member out of an array and hash of the data you don't want to take, you get the odd result.

Let's take a look at an example:

First, remember [1, 2, 3] Creates an anonymous array that contains (1, 2, 3), and then returns an array of ' references '.

Now think about this:

@a = ([1, 2, 3],
[4, 5, 6],
[7, 8, 9]
@a is an array of three members, each member being a ' reference ' to another array.

$a [1] is one of the ' references '.  It points to an array that contains (4, 5, 6), because this is a ' reference ' to an array, and using rule 2 tells us to write $a [1]->[2] to get the third member of the array. The $a [1]->[2] value is 6. Similarly, the $a [0]->[1] value is 2. Here we are like using a two-dimensional array; You can use the $a [row]->[column] to get or set the members of any column in any row in the array.

These symbols still seem to be a bit of a hassle, so there's a simpler use:

Arrow symbol rules
The arrows between the two subscript are optional.

We can use this notation $a[1][2] instead of $a[1]->[2]; they are the same. Relative to $a[0]->[1] = 23, we write $a[0][1] = 23; they are also the same.

Now they look really like two-dimensional arrays!

You can see why the arrows are so important. Without them, we have to write ${$a [1]}[2], not $a[1][2]. For three-dimensional arrays, they allow us to simply write $x[2][3][5] rather than write hard to read ${${$x [2]}[3]}[5].

The following is a solution to the problem mentioned earlier, that is, the reformatting of the city and the name of the country.

Copy Code code as follows:

while (<>) {
My ($city, $country) = split/,/;
$table {$country} = [] unless exists $table {$country};
Push @{$table {$country}}, $city;
foreach $country (sort keys%table) {
Print "$country:";
My @cities = @{$table {$country}};
Print join ', ', sort @cities;
Print ". N";

The program is divided into two parts: the 2--7 line completes the input of the data and the creation of the structure. 第8-13 the data and print the report. We set up a hash%table, its key is the country name, its health value is the name of the country corresponding to the city name of the ' reference ' array. This data structure looks as follows:

|   |   | +-----------+--------+
| germany| *---->| Frankfurt | Berlin |
|   |   | +-----------+--------+
|   |   | +----------+
| finland| *---->| Helsinki |
|   |   | +----------+
|   |   | +---------+------------+----------+
| USA | *---->| Chicago | Washington | New York |
|   |   | +---------+------------+----------+
Let's analyze the output section first. Assuming we already have this structure, how do we output it?

Copy Code code as follows:

foreach $country (sort keys%table) {
Print "$country:";
My @cities = @{$table {$country}};
Print join ', ', sort @cities;
Print ". N";

%table is an ordinary hash, from which we can get a column of keys, sort the keys, and iterate through all the keys. The only use of ' references ' here is line 10th. $table {$country} view the key $country in the hash and get its value. This health value is the ' reference ' of the city array in the corresponding country. Using Rule 1 tells us that you can recover the entire array by using the @{$table {$country}}. Line 10th is like

@cities = @array;
The difference is that the name of the array here is replaced by the ' reference ' {$table {$country}}}. The symbol @ tells Perl to get the entire array. After we get the list of cities, we sort them, merge the city names, and print them out.

The 第2-7 line is responsible for creating data structures, as follows:

Copy Code code as follows:

while (<>) {
My ($city, $country) = split/,/;
$table {$country} = [] unless exists $table {$country};
Push @{$table {$country}}, $city;

第2-4 Line gets the name of the city and country. Line 5th to see if this country name has been stored as a key in the hash, if not, the program creates a new, empty, anonymous array using the symbol [] (Create Rule 2) and puts a ' reference ' to the anonymous array as a health value in the hash.

The 6th row will place the city name in the corresponding array. $table {$country} now holds a ' reference ' that points to an array of cities of the corresponding country. Line 6th is like

Push @array, $city;
The difference is that the array name here is replaced by {$table {$country}}. Command push adds the city name to the end of the array with this ' reference '.

Here's one of the main points I overlooked. Line 5th is not required. We can take it off.

Copy Code code as follows:

while (<>) {
My ($city, $country) = split/,/;
# # # $table {$country} = [] unless exists $table {$country};
Push @{$table {$country}}, $city;

If there is already a record of the country name $country in the hash%table, there is no difference between the 5th line and the addition. The 6th line navigates itself to the $table{$country} This ' reference ' array, placing the value $city in the array. But if you don't have that key in%table, like Greece, what does it do?

This is Perl, and it will do its job accurately. If you want to assign a Athens to an array that doesn't exist, Perl will help you create a new, empty, anonymous array, put it in a hash%table, and then place the value Athens in the array. This is called ' automatic generation '--let things come out of themselves automatically. Perl found no such key in the hash and automatically created a new hash record. Perl finds that you want to use an array as the health value of a hash, it automatically creates an empty array of anonymous, and puts the ' references ' to that array in the same Harry. In general, Perl creates an array of only one member size, which is used to save the new city name.

Other highlights
I promise to give you 90% of the benefit of 10% details, which means I skipped over 90% of the details of the knowledge. Now look at the important part of this, which is much easier than reading the Perlref manpage, and the manual discusses 100% details.

Manual The Perlref manpage Some of the highlights:

You can create ' references ' to anything, including scalars, functions, and other references.

In using Rule 1, you can omit the curly brace when it is a scalar quantity such as $aref inside the curly braces. For example, @ $aref and @{$aref} are the same, $ $aref [1] and ${$aref}[1] are the same. If you are a beginner, it is recommended that you develop the habit of adding curly braces.

The following action does not copy ' reference ' to an array:
$aref 2 = $aref 1;
You'll get two ' references ' and they all point to the same array. If you modify the value of $aref1->[23], then when you look at the variable $aref2->[23, it also changes accordingly.

To copy this array, you need to do this

$aref 2 = [@{$aref 1}];
Use the symbol [...] to create a new anonymous array, and the ' reference ' of the new array is assigned to $AREF2. The new array is initialized with the contents of the array referenced by ' reference ' $aref 1.

Similarly, to copy an anonymous hash, you need this

$href 2 = {%{$href 1}};

If you want to determine if the contents of a variable are not ' references ', use the function ref. If its argument is ' reference ', the return value is ' true '. In fact, it does better: if it's a hash reference, it returns ' hash ', and if it's a reference to an array, return ' array '.

If you want to use a ' reference ' like a string, the string you get is like
ARRAY (0X80F5DEC) or HASH (0X826AFC0)
If you see a string like this, you should know that you have erroneously exported a ' reference '.

Another effect of this presentation is that you can use EQ to compare two ' references ' to see if they point to the same thing. (you can usually use = = to compare, because it will be more)

You can use a string just as you would use a ' reference '. If you use "foo" as a ' reference ' to an array, it is a reference to the @foo of the array. This is called a ' soft reference ' or ' symbolic reference '. Using the affirm use strict ' refs ' can cancel this function, if you accidentally use it, will cause various possible errors.

You might prefer to view the perllol manpage instead of the manual the Perlref manpage; it discusses in detail the list of lists and the multiple-weft arrays. You can then continue to study the manual the Perldsc manpage, which is the cookbook of the data structure, which provides methods for handling hashes of arrays, arrays, and other data structures.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.