Learning Perl 4ed Reading Notes-Chapter3 lists and Arrays

Source: Internet
Author: User
Tags scalar
1. List and array. The list mentioned in this book is a data structure. array is the data type used to store the list in Perl. In most cases, these two words can be exchanged, meaning the same. Unlike C, the Perl array does not need to define the element type. That is to say, each element in the array in Perl can be number or string. The element types are not necessarily the same. In the same way as C, the access to the array is carried out through the subscript, And the array subscript of the first element is 0.

2. There is no difference between using arrays in Perl and using arrays in C:

$ Fred [0] = "Yabba ";
$ Fred [1] = "Dabba ";
$ Fred [2] = "Doo ";
Print $ Fred [0];
$ Fred [2] = "diddley ";
$ Fred [1]. = "whatsis ";

If the given subscript is incorrect, UNDEF is returned:

$ Blank = $ Fred [142_857]; # unused array element gives UNDEF
$ Blanc = $ mel; # unused scalar $ Mel also gives UNDEF

3. special array indices. one interesting thing about the array in Perl is that if the subscript of the accessed array exceeds the limit (the size of the array is exceeded), Perl will not make an error and Perl will automatically resize the array for us:

$ Rocks [0] = 'Bedrock'; # One element...
$ Rocks [1] = 'slate'; # Another...
$ Rocks [2] = 'lava'; # And another...
$ Rocks [3] = 'crushed Rock'; # And another...
$ Rocks [99] = 'schist'; # Now there are 95 UNDEF Elements

In the above example, the rocks array finally becomes 100 elements, with 95 UNDEF elements in the middle.

4. we can use $ # rocks to obtain the index value of the last element of the array. For example, $ # rocks will get 99. Note that this value is actually 1 less than the number of array elements, because the first element starts from 0, $ # Rocks returns the index value of the last element instead of the array size 5. list literals. this section describes how to define a list using hard code. Perl defines a list in a very flexible way, such:

(1, 2, 3) # list of three values 1, 2, and 3
(1, 2, 3,) # The same three values (the trailing comma is ignored)
("Fred", 4.5) # two values, "Fred" and 4.5
() # Empty list-zero elements
(1 .. 100) # list of 100 Integers

(1 .. 5) # Same as (1, 2, 3, 4, 5)
(5.7) # Same thing-both values are truncated
(5 .. 1) # Empty list-... only counts "uphill"
(0, 2 .. 6, 10, 12) # Same as (0, 2, 3, 4, 5, 6, 10, 12)
($ M .. $ n) # range determined by current values of $ m and $ n
(0 .. $ # Rocks) # The indices of the rocks array from the previous section
("Fred", "Barney", "Betty", "Wilma", "Dino ")

As shown in the preceding example, you can use variables when defining a list. In this way, the value of a list is not completely static or dynamic.

In addition, note that when using..., it can only be uphill, that is, (5 .. 1. The reverse operator will be introduced later. You can flip the content in the list.

6. "QW" shortcut cut. QW is a shortcut, which means "quoted words" or "quoted by whitespace". Using QW allows us to quickly define a string list. If QW is used, each string can be enclosed by no quotation marks, in this way, we can omit some typing tasks:

QW (Fred Barney Betty Wilma Dino)
It is equivalent
("Fred" "Barney" "Betty" "Wilma" "Dino ")

In addition, it is very good to define a string list with QW in Perl. delimiter can choose freely:

QW! Fred Barney Betty Wilma Dino!
QW # Fred Barney Betty Wilma Dino # Like in a comment!
QW (Fred Barney Betty Wilma Dino)
QW {Fred Barney Betty Wilma Dino}
QW [Fred Barney Betty Wilma DINO]
QW <Fred Barney Betty Wilma Dino>

Here we can see that not only () is used to enclose strings, but other characters can be used as long as the two delimiter are a pair of symbols or the same char.

However, it should be noted that the list literals stated by QW, each string is equivalent to a single quotation mark, so variables cannot be used in the string, and many backslash escaping cannot be used. In addition, if our string contains delimiter itself, use backslash escape:

QW! Yahoo \! Google excite Lycos! # Include Yahoo! As an element

It is good to use a variety of characters as delimiter, for example:

Code: select all

As mentioned above, if we want to use a Unix path as a string, we can use non-// characters as delimiter. If Perl requires that only/be used as delimiter, the above code will be very difficult to read.

. In addition, for convenience, Perl also defines some special array subscript, such as the negative value array index, the most commonly used is-1, which indicates the last element of the array, the following two codes have the same effect:

$ Rocks [-1] = 'hard Rock ';
$ Rocks [$ # Rocks] = 'hard Rock ';

-2,-3... and so on, but generally we only use one-1, and the other is of little practical significance.

7. list assignment. This section describes how to assign values to a list. Note that list is not an array. For example:

($ Fred, $ Barney, $ Dino) = ("Flintstone", "rubble", UNDEF );

In this way, you can assign values to the three variables. These three variables can be understood as a list. Therefore, we can easily exchange the values of two variables without passing an intermediate variable:

($ Fred, $ Barney) = ($ Barney, $ Fred); # swap those values
($ Betty [0], $ Betty [1]) = ($ Betty [1], $ Betty [0]);

What if the list of values assigned on the right is more or less than the variable on the left? It is very simple. If the value is too large, it will be ignore. If there are more variables, all the extra variables will be assigned as UNDEF:

($ Fred, $ Barney) = QW <Flintstone rubble slate granite >;# two ignored items
($ Wilma, $ Dino) = QW [Flintstone]; # $ Dino gets UNDEF

Note that <> and [] After QW are delimiter and have no special meaning.

8. @ symbol. Perl provides an @ symbol to access the entire array/list. For example:

@ Rocks = QW/bedrock slate lava /;
@ Tiny = (); # The empty list
@ Giant = 1 .. 1e5; # A list with 100,000 Elements
@ Stuff = (@ giant, UNDEF, @ giant); # A list with 200,001 Elements
$ Dino = "granite ";
@ Quarry = (@ rocks, "Crushed Rock", @ tiny, $ Dino );

As shown above, @ can be used to access the entire array, which is very convenient. Therefore, @ copy = @ quarry; is used to assign all elements in the array quarry to the copy array.

9. Pop and push operators. Pop is to delete the last element of the array and return this element. Push is to add an element to the end of the array and add the length of the array to 1. As mentioned above, the array index can also be used to achieve this (when accessing an index that exceeds the length of the array, Perl will automatically expand the array to this size for us, without errors ), why don't I use index? I want to create pop and push specifically? It is very simple. First, it is better understood with push and pop. Second, it has higher performance with push and pop, because when using index, especially when accessing an index that exceeds the length of the array, perl triggers an internal exception and then processes the exception. This process involves many tasks, resulting in low performance. Therefore, unlike C, Perl encourages us to use push and pop to operate the elements at the end of the array.

@ Array = 5 .. 9;
$ Fred = POP (@ array); # $ Fred gets 9, @ array now has (5, 6, 7,
$ Barney = pop @ array; # $ Barney gets 8, @ array now has (5, 6, 7)
Pop @ array; # @ array now has (5, 6). (The 7 is discarded .)

Push (@ array, 0); # @ array now has (5, 6, 0)
Push @ array, 8; # @ array now has (5, 6, 0,
Push @ array, 1 .. 10; # @ array now has those 10 new elements
@ Others = QW/9 0 2 1 0 /;
Push @ array, @ others; # @ array now has those five new elements (19 total)

If we pop an empty array, UNDEF is returned.

10. Shift and unshift operators. Unlike push and pop, the difference is that shift/unshift operations are elements starting with an array.

@ Array = QW # Dino Fred Barney #;
$ M = shift (@ array); # $ M gets "Dino", @ array now has ("Fred", "Barney ")
$ N = shift @ array; # $ n gets "Fred", @ array now has ("Barney ")
Shift @ array; # @ array is now empty
$ O = shift @ array; # $ o gets UNDEF, @ array is still empty
Unshift (@ array, 5); # @ array now has the one-element list (5)
Unshift @ array, 4; # @ array now has (4, 5)
@ Others = 1 .. 3;
Unshift @ array, @ others; # @ array now has (1, 2, 3, 4, 5)

When shift is an empty array, UNDEF is returned.

11. interpolating arrays into strings. This section describes how to reference an array in a string-of course, in a double quotation mark string.

@ Rocks = QW {Flintstone slate rubble };
Print "quartz @ rocks limestone \ n"; # prints five rocks separated by Spaces

You can use the @ symbol to reference the entire array and use $ array [Index] to reference an element in the array.

Here, when assigning values to a list, all elements are separated by spaces by default. We can change this default behavior, which is the same as shell programming. In Perl, by redefinition of $, you can set the default delimiter to distinguish all elements in the list.

When you reference the entire array, no space is displayed before and after the printed string. Therefore, we need to manually add spaces to the string.

12. as we can see above, we use the @ symbol to reference the entire array, so we will naturally encounter the problem that when our string is an email address (containing the @ symbol ), so, we need to use backslash to escape, otherwise Perl will think that we reference an array in this string, rather than an email address, such:

$ Email = "fred@bedrock.edu"; # wrong! Tries to interpolate @ Bedrock
$ Email = "Fred \ @ bedrock.edu"; # correct
$ Email = 'fred @ bedrock.edu'; # Another way to do that

13. Summary. Example:

@ Fred = QW (Hello Dolly );
$ Y = 2;
$ X = "this is $ Fred [1]'s place"; # "this is Dolly's place"
$ X = "this is $ Fred [$ Y-1]'s place"; # Same thing

Here we reference an element in the array, and note that in $ Fred [$ Y-1], Perl only mechanically replaces $ y with 2, if $ Y = 2*4, Perl simply replaces $ y with 2*4 instead of 8. If we enable warning, perl interprets 2*4 as 2 (because Perl requires a number to perform the-1 operation, and Perl performs automatic type conversion according to what we learned earlier ). 10 million notes.

@ Fred = QW (eating rocks is wrong );
$ Fred = "right"; # We are trying to say "this is right [3]"
Print "this is $ Fred [3] \ n"; # prints "wrong" using $ Fred [3]
Print "this is $ {Fred} [3] \ n"; # prints "right" (protected by braces)
Print "this is $ Fred". "[3] \ n"; # Right again (different string)
Print "this is $ Fred \ [3] \ n"; # Right again (backslash hides it)

In this example, we use {} to forcibly display and define variables to separate the array Fred from the variable Fred (the names of arrays and variables in Perl can be the same, because they have different types, but we strongly recommend that you do not do this, because it is difficult to find it ).


14. foreach control structure. foreach can traverse a list cyclically, which is similar to the loop in shell programming. For example:

Code: select all
foreach $rock (qw/ bedrock slate lava /) {
  print "One rock is $rock.\n";  # Prints names of three rocks

Foreach has a very important key point: control variable ($ rock in the above example) in foreach, not a copy of the variable in the list, but the variable itself, in other words, if control variable is modified in foreach, the data in the list will be modified. In this example, \ t and \ n are added to each element in the list:

Code: select all
@rocks = qw/ bedrock slate lava /;
foreach $rock (@rocks) {
  $rock = "\t$rock";       # put a tab in front of each element of @rocks
  $rock .= "\n";           # put a newline on the end of each
print "The rocks are:\n", @rocks; # Each one is indented, on its own line

15. in addition, the control variable of foreach also has a note that Perl will automatically back up the control variable before the foreach loop starts. When the foreach loop ends, perl automatically restores the value of control variable to the value before the foreach loop, which is different from that of C. In other words, we don't have to worry about changing the value of control variable at the beginning and end of the loop, but as described at above, changes to control variable in the foreach loop directly affect the values of corresponding variables in the list.

16. Perl's favorite default: $ _. $ _ Is an important and common variable in Perl. It is the default variable in Perl. When no variable is specified in our code, $ _ is the default variable. For example:

Code: select all
foreach (1..10) {  # Uses $_ by default
  print "I can count to $_!\n";

As shown above, if no control variable is specified in foreach, $ _ becomes control variable. Another example is:

$ _ = "Yabba dabba doo \ n ";
Print; # prints $ _ by default

Since print does not specify the print variable, Perl prints the $ _ variable value.

17. reverse operator. reverse is used to reverse a list. For reverse, you only need to remember that reverse will not modify the List itself, and reverse will return the result after the flip as the return value. If we want to modify the List itself, you only need to assign the return value of reverse to the List itself.

@ Fred = 6... 10;
@ Barney = reverse (@ Fred); # gets 10, 9, 8, 7, 6
@ Wilma = reverse 6 .. 10; # gets the same thing, without the other Array
@ Fred = reverse @ Fred; # puts the result back into the original array

Reverse @ Fred; # wrong-doesn't change @ Fred
@ Fred = reverse @ Fred; # That's better

18. sort operator. sort is used to sort the items in a list. By default, sort is sorted by ASCII code table, that is, upper-case letters are placed before lower-case letters and numbers are placed before letters, punctuation is everywhere in the ASCII code table. Chapter 1 describes how to customize the sorting logic of sort. Like reverse, sort does not modify the List itself. Sort returns the sorted result as the return value. to modify the List itself, you must re-assign the return value of sort to the List itself.

@ Rocks = QW/bedrock slate rubble granite /;
@ Sorted = sort (@ rocks); # Gets bedrock, granite, rubble, slate
@ Back = reverse sort @ rocks; # These go from slate to bedrock
@ Rocks = sort @ rocks; # Puts sorted result back into @ rocks
@ Numbers = sort 97 .. 102; # Gets 100,101,102, 97, 98, 99

Note that in the last example, the sorting result is 100 in the first place, because it is sorted according to the ASCII code table.

Sort @ rocks; # Wrong, doesn' t modify @ rocks
@ Rocks = sort @ rocks; # Now the rock collection is in order

19. scalar and list context. this section is the most important part of this chapter. In fact, this section describes the different behaviors of variables of scalar and list types in different contexts, it is like a word in a language has different meanings in different contexts. The context here refers to an environment where the variable is located and an expression.

20. For example:

42 + something # The something must be a scalar
Sort something # The something must be a list

@ People = QW (Fred Barney Betty );
@ Sorted = sort @ people; # list context: Barney, Betty, Fred
$ Number = 42 + @ people; # scalar context: 42 + 3 gives 45

Let's look at this example. People is a list. In the last code, we add a scalar variable and people. @ people returns the number of elements in the list, instead of the List itself, this is the different performance of the same variable in different contexts.
Generally, to determine the true performance of a variable, we should first look at the variable type on the left of the equal sign, in this way, we determine the type of variable (scalar or list) that the expression on the right of the equal sign should give. Then, the variables in expression will give different interpretation methods according to such requirements. Examples include:

@ List = @ people; # A list of three people
$ N = @ people; # The number 3

21. More examples and rules are provided. For example, using sort in a list context is normal. Using sort in a scalar context, sort returns UNDEF; using reverse in a list context, reverse sorts all list elements in reverse order. If reverse is used in scalar context, reverse returns a reverse string:

@ Backwards = reverse QW/yabba dabba doo/; # Gives Doo, Dabba, yabba
$ Backwards = reverse QW/yabba dabba doo/; # Gives oodabbadabbay

Here are more examples:

$ Fred = something; # scalar context
@ Pebbles = something; # list Context
($ Wilma, $ Betty) = something; # list Context
($ Dino) = something; # Still list context!

Note that in the last example, the left side of the equals sign is a list, not a scalar variable.

22. Let's look at the example. The example here is to assign the scalar variable to a list type variable:

@ Fred = 6*7; # gets the One-element list (42)
@ Barney = "hello". ''." world ";
@ Wilma = UNDEF; # Oops! Gets the One-element list (UNDEF)
# Which is not the same as this:
@ Betty = (); # a correct way to empty an array

23. Perl provides a keyword called scalar. With this keyword, You can manually force a variable to be of the scalar type, such:

@ Rocks = QW (talc quartz Jade obsidian );
Print "How many rocks do you have? \ N ";
Print "I have", @ rocks, "rocks! \ N "; # Wrong, prints names of Rocks
Print "I have", scalar @ rocks, "rocks! \ N "; # correct, gives a number

In the third code, Print prints every element in the array rocks, and we want print to print the size of this array. In the fourth code, we use the scalar keyword to prompt Perl. Here @ rocks is interpreted as the scalar variable, so the size of this array is printed.

24. <stdin> in list context. we have introduced how to use <stdin> to read a row (read from a file or keyboard) and assign it to a scalar variable; this section describes the scenario where <stdin> is used in list context. The result is that <stdin> reads end-of-file all the time, then, assign the strings of each row as an element in the list:

@ Lines = <stdin>; # Read standard input in list Context

Lines is a list, so if <stdin> is a file at this time, it will always read the end of the file, and each line is assigned to this list as an element; if <stdin> is a keyboard, the string entered in each line is assigned to this list as an element until the user presses Ctrl + d (in Linux/Unix systems, of course, this key combination can be redefined using the stty command. In Windows, press Ctrl + Z to indicate EOF ).

In this way, the string read from each row has a \ n at the end. Like the previous one, we can use chomp to remove the \ n at the end of the row. But interestingly, chomp can also be used in list context. In this case, Chomp removes \ n at the end of each element string in the list, which is very convenient!

Chomp (@ lines = <stdin>); # read the lines, not the newlines

However, when using the <stdin> feature, you should also pay attention to some performance issues, such as what happens when you read a MB log file at a time? As in the past, Perl will not limit the size of this size, as long as memory is enough, but when we do this, we will use about 1 GB of memory space. If the memory is not enough, you need to be careful. If the memory is enough, there will naturally be no problem.


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.