Perl-create and reference a hash

Source: Internet
Author: User
Syntax
There are only two ways to create a 'quot.

Create reference

Create Rule 1
If you add a '/' sign before a variable, you will get the 'quota' of the variable '.

$ Aref = // @ array; # $ Aref saves the 'quot' pointing to @ Array'
$ Href =/% hash; # $ href stores the 'quot' pointing to % hash'
When you save the 'quot' in a variable similar to $ Aref or $ href, you can copy or save it like other scalar operations.

$ Xy = $ Aref; # $ XY now saves the 'quot' pointing to @ Array'
$ P [3] = $ href; # $ P [3] Now stores the 'reference' pointing to % hash'
$ Z = $ P [3]; # $ z now saves the 'quota' pointing to % hash'
These examples demonstrate how to create a 'quot' for a named variable, but sometimes the array or hash we create has no name. This is similar to the string '/N' or the number '80' that you have not put in the variable.

Create Rule 2

[Items] creates a new anonymous array and returns a 'quot' pointing to the array '. {Items} creates a new anonymous hash and returns a 'quota' for that hash '.

$ Aref = [1, "foo", UNDEF, 13];
# $ Aref saves the 'quot' of this array'
$ Href = {APR =>; 4, Aug =>; 8 };
# $ Href saves the 'quot' of the hash'
The 'quota' obtained from Rule 2 is of the same type as the 'quota' obtained from Rule 1:

# Here:
$ Aref = [1, 2, 3];
# Same as above:
@ Array = (1, 2, 3 );
$ Aref = // @ array;
The first method is the abbreviation of the last two rows. Except for the first method, no Redundant Array variable @ array is created.

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.

Use reference
After you create a 'quot', what operations can you perform on it? It is a scalar, and you can save and retrieve it like any scalar. In addition, there are two ways to use:

Rule 1
You can always use an array with braces to 'quot' to replace the name of an array. For example, replace @ {$ Aref} with @ array.

The following is an example of usage:

Array:

@ A @ {$ Aref} An Array
Reverse @ a reverse @ {$ Aref} sorts an array in reverse order.
$ A [3] $ {$ Aref} [3] a member in the array
$ A [3] = 17; $ {$ Aref} [3] = 17 assign a value to a member
In each line above, the two expressions implement the same function. On the left is the @ A operation on the array, and on the right is the operation on the array pointed to by 'quot' $ Aref. They have the same effect on arrays.

The 'quota' of the hash is exactly the same as the 'quota' of the array.

% H % {$ href} a hash
Keys % H keys % {$ href} get the key from the hash
$ H {'red'} $ {$ href} {'red'} is a member in the hash.
$ H {'red'} = 17 $ {$ href} {'red'} = 17 assign values to a member
No matter what you want to do with a 'quot', rule 1 has already told you how to do it. You only need to write Perl code like using a regular array or hash, and then replace the array or hash name with {$ reference. 'How can I traverse the entire array when I only have one 'quot? 'You write like this:

For my $ element (@ array ){
...
}
Then replace array name @ array with 'quot:

For my $ element (@ {$ Aref }){
...
}
'How can I print a hash when I only have one 'quot? 'Write a code that prints the entire hash first:

For my $ key (Keys % hash ){
Print "$ key =>; $ hash {$ key}/N ";
}
Then replace the hash name with 'quota:

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

Rule 2
Rule 1 is what you really need, because it tells you how to handle a 'quot', and it is effective for almost any 'quot. But what we usually do is only related to a member in an array or hash. Using Rule 1 is a very cumbersome method, so there is a simple method.

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

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

If $ Aref stores an array 'quot', $ Aref-> [3] is the fourth member of the array. Do not confuse with $ Aref [3]. This represents the fourth member of a completely different array. the confusing array is @ Aref. Variables $ Aref and @ Aref are completely irrelevant, just like $ item and @ item.

Similarly, $ href-> {'red'} is a part of the variable $ href of the hash 'quota', or even a hash without a name. $ Href {'red'} is part of another confusing name hash % href. It is easy to forget to write the '->' symbol. In this case, when your program extracts members from an array and hash that you do not want to fetch data, you will get a strange calculation result.

Example
Let's take an example:

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

Think about it now:

@ A = ([1, 2, 3],
[4, 5, 6],
[7, 8, 9]
);
@ A is an array with three members. Each member is a 'quota' of another array '.

$ A [1] is a 'quot '. It points to an array, which contains (4, 5, 6), because this is an array 'quot ', using Rule 2, we can write $ A [1]-> [2] to obtain the third member of this array. The value of $ A [1]-> [2] is 6. Similarly, the value of $ A [0]-> [1] is 2. Here we are using a two-dimensional array. You can use $ A [row]-> [column] to retrieve or set members in any row or column in the array.

These symbols seem to be a little troublesome, so there are more simple usage:

Arrow symbol rules
The Arrow between two subscripts is optional.

We can use $ A [1] [2] to replace $ A [1]-> [2]; they are the same. Compared with $ A [0]-> [1] = 23, we write $ A [0] [1] = 23; they are the same.

Now they look like a two-dimensional array!

You can see why arrows are so important. Without them, we must write $ {$ A [1]} [2] instead of $ A [1] [2]. For 3D arrays, they allow us to simply write $ X [2] [3] [5] instead of the $ {$ {$ X [2]} [3]} [5] method that is hard to read..

--------------------------------------------------------------------------------

Solution
The following is a solution to the problem mentioned above, that is, reformat the city and country names.

1 My % table;
2 while (<> ){
3 chomp;
4 my ($ City, $ country) = Split /,/;
5 $ table {$ country} = [] Unless exists $ table {$ country };
6 push @ {$ table {$ country}, $ city;
7}
8 foreach $ country (sort keys % table ){
9 print "$ country :";
10 My @ cities =@{$ table {$ country }};
11 print join ',', sort @ cities;
12 print "./N ";
13}
This program is divided into two parts: Row 2-7 to complete data input and data structure creation. 8th-13 rows analyze the data and print the report. We have set a hash % table. Its key is the country name, and its key value is the 'quot' of the array of city names corresponding to the country name '. The data structure looks like this:

% Table
+ ------- + --- +
| + ----------- + -------- +
| Germany | * ----> | Frankfurt | Berlin |
| + ----------- + -------- +
+ ------- + --- +
| + ---------- +
| Finland | * ----> | Helsinki |
| + ---------- +
+ ------- + --- +
| + --------- + ------------ + ---------- +
| USA | * ----> | Chicago | Washington | New York |
| + --------- + ------------ + ---------- +
+ ------- + --- +
Let's analyze the output section first. If we already have this structure, how can we output it?

8 foreach $ country (sort keys % table ){
9 print "$ country :";
10 My @ cities =@{$ table {$ country }};
11 print join ',', sort @ cities;
12 print "./N ";
13}
% Table is a normal hash from which we can obtain a column of keys, sort the keys, and traverse all the keys. Here, the only use of 'quot' is 10th rows. $ Table {$ country} checks the hash key $ country and obtains its value. This parameter indicates the 'quot' of the corresponding country's urban array '. Rule 1 indicates that you can use @ {$ table {$ country} to restore the entire array. The 10th rows are like

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

Line 2-7 is responsible for creating the data structure as follows:

2 while (<> ){
3 chomp;
4 my ($ City, $ country) = Split /,/;
5 $ table {$ country} = [] Unless exists $ table {$ country };
6 push @ {$ table {$ country}, $ city;
7}
Obtain the name of the city and country from lines 3 to 4. Check whether the country name is already in the hash as a key. If not, the program uses the symbol [] (Create rule 2) create a new, empty anonymous array, and put a 'quot' pointing to this anonymous array as the key value in the hash.

The city name will be placed in the corresponding array. $ Table {$ country} Now stores a 'quot' that points to an array of cities in the corresponding country. The 6th rows are like

Push @ array, $ city;
The difference is that the array name here is replaced by {$ table {$ country. Command push to add the city name to the 'quot' to point to the end of the array.

I ignored a key point here. The 5th rows are not required. We can remove it.

2 while (<> ){
3 chomp;
4 my ($ City, $ country) = Split /,/;
5 #### $ table {$ country} = [] Unless exists $ table {$ country };
6 push @ {$ table {$ country}, $ city;
7}
If the country name $ country record already exists in the hash % table, there is no difference in adding no 5th rows. In the 6th rows, locate the 'quot' array pointed to by $ table {$ country} and put the value $ city into the array. But what if there is no such key in % table, such as Greece?

This is Perl, which completes the work accurately on its own. If you want to assign an Athens value to an array that does not exist, Perl will help you create a new, empty anonymous array and put it in the hash % table, then put the value Athens in this array. This is called "auto generate"-to make things automatically generate. Perl automatically creates a new hash record without this key in the hash. Perl finds that you want to use an array as the hash key. It automatically creates an anonymous empty array and places the 'quot' pointing to this array in that hash. Generally, an array created by Perl has only one member size, which is used to save the new city name.

--------------------------------------------------------------------------------

Other highlights
I promise to give you 10% of the benefits with 90% of the details, which means I skipped 90% of the details. Now let's take a look at the important part. This is much easier than reading the perlref manpage. The manual discusses 100% of the details.

Some highlights in the manual The perlref manpage:

You can create a 'quot' for anything, including scalar, function, and other references.

When rule 1 contains a scalar variable like $ Aref, You can omit this variable. For example, @ $ Aref and @ {$ Aref} are the same, and $ Aref [1] and $ {$ Aref} [1] are the same. If you are a beginner, we suggest you still develop the habit of adding braces.

The following operations do not copy the array pointed to by 'quot:
$ Aref2 = $ aref1;
You will get two 'reference', both pointing to the same array. If you modify the value of $ aref1-> [23], it also changes when you view the variable $ aref2-> [23.

To copy this array, you need

$ Aref2 = [@ {$ aref1}];
Use the [...] symbol to create a new anonymous array, and the 'quote' of the new array is assigned to $ aref2. The new array is initialized with the content of the array pointed to by 'referencing' $ aref1.

Similarly, to copy an anonymous hash, you need

$ Href2 ={%{$ href1 }};

If you want to determine whether the content stored in a variable is 'quota', use the function ref. If its parameter is 'quot', the returned value is 'true '. In fact, it is better: if it is a hash reference, it returns 'hash'. If it is an array reference, it returns 'array '.

If you want to use 'quot' 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 mistakenly output a 'quot '.

Another function of this display method is that you can use EQ to compare two 'reference' to see if they point to the same thing. (You can usually use = for comparison, because it is better)

You can use a string like 'quot. If you use "foo" as an array 'quot', it is a reference pointing to array @ Foo. This is called 'soft quot' or 'symbol quot '. Using the declarative use strict 'refs' can cancel this function. If you accidentally use it, various possible errors may occur.

You may prefer viewing the perllol manpage, rather than the manual The perlref manpage; it discusses in detail the list and multi-latitude arrays. Then, you can continue to learn the manual The perldsc manpage; it is a data structure cookbook that provides methods for processing hash arrays, array hashing, 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: info-contact@alibabacloud.com 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.