Lists and arrays in Perl learning notes _perl

Source: Internet
Author: User
Tags array length chop numeric value perl interpreter scalar stdin


One, List



A list is a sequence of values enclosed in parentheses that can be any value or NULL, such as: (1, 5.3, "Hello", 2), empty list: ().
Note: A list containing only one numeric value (for example: (43.2)) is different from the value itself (that is, 43.2), but they can be converted or assigned to each other. List example:


Copy Code code as follows:

($var, "a string")
(Num << 2)
($var 1 + $var 2)
($value, "The answer is $value")

Second, array--the storage of the list





The list is stored in an array variable, and unlike a simple variable, the array variable starts with the character "@", such as:


Copy Code code as follows:

@array = (1, 2, 3);

Note:
(1) When an array variable is created, the initial value is an empty list: ().
(2) Because Perl uses @ and $ to differentiate between array variables and simple variables, the same name can be used for both array variables and simple variables, such as:
Copy Code code as follows:

$var = 1;
@var = (one, 27.1, "a string");

But this is easy to confuse, so it is not recommended.





1, access to the array



The values in the array are accessed by subscript, and the first element is labeled 0. An attempt is made to access an array element that does not exist, but the result is null, but if an element that exceeds the size of the array is assigned, the array is automatically grown and the element value that was not originally null. Such as:


Copy Code code as follows:

@array = (1, 2, 3, 4);
$scalar = $array [0];
$array [3] = 5; # now @array is (1,2,3,5)
$scalar = $array [4]; # now $scalar = null;
$array [6] = 17; # now @array is (1,2,3,5, "", "", 17)

Copy between arrays
Copy Code code as follows:

@result = @original;

Assigning values to lists with arrays
Copy Code code as follows:

@list1 = (2, 3, 4);
@list2 = (1, @list1, 5); # @list2 = (1, 2, 3, 4, 5)

The assignment of an array to a simple variable

(1) @array = (5, 7, 11);
Copy Code code as follows:

($var 1, $var 2) = @array; # $var 1 = 5, $var 2 = 7, 11 ignored

(2) @array = (5, 7);
Copy Code code as follows:

($var 1, $var 2, $var 3) = @array; # $var 1 = 5, $var 2 = 7, $var 3 = "" (NULL)

Assign values to variables from standard input (STDIN)
Copy Code code as follows:

$var =;
@array =; # ^d The symbol for the end input

2, square brackets and variable substitution in the string
Copy Code code as follows:

"$var [0]" is the first element of the array @var.
' $var \[0] ' escapes the character ' [', which is equivalent to ' $var '. ' [0] ', $var replaced by a variable, [0] remains unchanged.
"${var}[0]" is also equivalent to "$var". [0] ".
"$\{var}" cancels the curly braces variable substitution function, contains the text: ${var}.

3, List scope:
Copy Code code as follows:

(1..10) = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
(2, 5..7, 11) = (2, 5, 6, 7, 11)
(3..3) = (3)

-For real numbers
Copy Code code as follows:

(2.1..5.3) = (2.1, 3.1, 4.1, 5.1)
(4.5..1.6) = ()

. for strings
Copy Code code as follows:

("AAA" ...) AAD ") = (" AAA "," AaB "," AAC "," AAD ")
@day_of_month = ("01" ...) 31 ")

. can contain a variable or an expression
Copy Code code as follows:

($var 1. $var 2+5)

. Tips:
Copy Code code as follows:

$fred = "Fred";
Print ("Hello,". $fred. "!\n") x 2);

The results are:
Copy Code code as follows:

Hello, fred!.
Hello, fred!.

4, the output of the array:
(1) @array = (1, 2, 3);
Copy Code code as follows:

Print (@array, "\ n");

Results are: 123
(2) @array = (1, 2, 3);
Copy Code code as follows:

Print ("@array \ n");

The results are: 1 2 3
5, List/array length
When an array variable appears where the expected simple variable appears, the Perl interpreter takes its length.
Copy Code code as follows:
@array = (1, 2, 3);
$scalar = @array; # $scalar = 3, that is, the length of the @array
($scalar) = @array; # $scalar = 1, that is, @array the value of the first element

Note: The length of the array as the number of cycles can be programmed as follows:
Copy Code code as follows:
$count = 1;
while ($count <= @array) {
Print ("element $count: $array [$count -1]\n");
$count + +;
}

6, Sub-array
Copy Code code as follows:
@array = (1, 2, 3, 4, 5);
@subarray = @array [0,1]; # @subarray = (1, 2)
@subarray2 = @array [1..3]; # @subarray2 = (2,3,4)
@array [0,1] = ("string", 46); # @array = ("string", 46,3,4,5) now
@array [0..3] = (11, 22, 33, 44); # @array = (11,22,33,44,5) now
@array [1,2,3] = @array [3,2,4]; # @array = (11,44,33,5,5) now
@array [0..2] = @array [3,4]; # @array = (5,5, "", 5,5) now

You can exchange elements in the form of a sub array:
Copy Code code as follows:
@array [1,2] = @array [2,1];

7, about the array of library functions
(1) sort--sorted by character order
Copy Code code as follows:
@array = ("This", "is", "a", "test");
@array2 = sort (@array); # @array2 = (' A ', ' is ', ' test ', ' this ')
@array = (70, 100, 8);
@array = sort (@array); # @array = (8) Now

(2) reverse--inverted array
Copy Code code as follows:

@array2 = reverse (@array);
@array2 = Reverse sort (@array);

(3) chop--array to tail
The meaning of the chop is to remove the last character, the line break, when the stdin (keyboard) input string is entered. And if it acts on an array, it does so with each element of the array.
Copy Code code as follows:
@list = ("Rabbit", "12345", "quartz");
Chop (@list); # @list = ("Rabbi", "1234", "quart") now

(4) join/split--connection/Split
The first parameter of the join is the intermediate character used for the connection, and the remainder is an array of characters to be concatenated.
Copy Code code as follows:
$string = Join ("", "This", "is", "a", "string"); # The result is ' this is a string '
@list = ("Words", "and");
$string = Join ("::", @list, "colons"); #the result is "Words::and::colons"
@array = Split (/::/, $string); # @array = ("Words", "and", "colons") now





-------------------------------------------------------
If you think of a scalar as the singular in Perl, the list and array are considered to be complex numbers in Perl.



A list is an ordered set of scalars. An array is a variable that contains a list. In Perl, the two terms are interchangeable. But in the strictest sense, the list refers to the data, and the array is its variable name. You can have some values (lists) but not arrays, but each array scalar has a list, although it can be empty.



Each element in the list is a separate scalar value. These values are sequential, that is, they have a fixed sequence from the beginning to the last element. An array or an element in a list is numbered, and its index starts with an integer 0, which in turn increases by one, so the index of the array or the first element of the list is 0.



Since each element is a separate scalar value, a list or array can contain numbers, strings, undef values, or combinations of scalar values of any different type. However, the types of these elements are usually consistent.



Lists and arrays can contain any number of elements. Contains at least 0 elements and can fill up your available memory. It also embodies the design philosophy of Perl, "no unnecessary restrictions".



1. Accessing array elements
in Perl, an element can be accessed by index value, such as: $array [0] = "Test";p rint $array [0];



Array names and scalars belong to completely different namespaces (namespace). The same program can also contain scalar variables called $array. Perl treats them as completely different things and does not confuse them. (Do not recommend this, easy to confuse)



2. Special array index
If you store an element at the back of the last element of the array, the array grows automatically. Perl has no length limitations, as long as you have enough memory. If Perl needs to create an element, its value is undef.



Sometimes you need to know the index of the last element of the array. An array of arrays, with the index of the last element being $ #array



An easy way: The negative index value of an array starts with the last element. But do not consider these indexes to be circular. If the array has 3 elements, the valid negative index value is-1 (the last Element),-2 (the middle element),-3 (the first element). In fact, almost no one uses a negative index value other than-1.



3. List
arrays are lists that are enclosed in parentheses and whose elements are separated by commas, which form the elements of an array.



The elements in the list do not have to be constants, or they can be expressions that evaluate the value when the statement is executed. The list can contain any scalar values.



4.QW abbreviation
practice has shown that lists of strings are often used in Perl. There is an easy way to achieve a similar function without entering a lot of quotes, which is using QW.



QW says "quoted words" or "quoted by whitespace," regardless of that interpretation, Perl treats them as single quotes strings, and you can't use \ n and QW in $fred like double quotes. whitespace (spaces, such as spaces,tabs,newlines, etc.) will be ignored, leaving the elements that make up the list.



Because QW is a reference, you cannot add comments within QW.



Note:perl allows any punctuation mark to be used as the QW list delimiter.



5. List Assignment
like scalar values, list values can also be assigned to variables:


Copy Code code as follows:

($fred [0], $fred [1], $fred [2]) = ("haha", "Wawa", undef);
Print $fred [0]. $fred [1]. $fred [2];

Each variable in the list on the left has a new value, and the result is the same as using 3 assignment statements. Because the list was established before the assignment, you can exchange the values of two variables in Perl using the following simple method.





Note: Perl has a simple way of writing when you want to reference this array. The array name is followed by an @ (with no brackets) to refer to the entire array.



6.pop and push operations
The pop operation takes the last element of the array out and returns:


Copy Code code as follows:

@array = 5..9;
Pop @array;
foreach $t (@array) {
Print $t;
}

You can use or not use parentheses after a pop. This is a general rule in Perl: If you remove the parentheses, the parentheses are optional.





The opposite of a pop is a push, which adds an element (or a list of elements) to the end of the array:


Copy Code code as follows:

@array = 5..9;
Push (@array, 0);
foreach $t (@array) {
Print $t;
}

The first parameter of the Note:push or the unique parameter of the pop must be an array variable.





7.shift and Unshift operations



The push and pop are operated at the end of the array, and accordingly, unshift and shift operate on the beginning of a set (with the smallest subscript element on the left side of the array).



8. Inserting an array into a string
like a scalar, an array can also be inserted into a string of double quotes. The inserted array element is automatically separated by a space.


Copy Code code as follows:

@rocks = Qw{wawa kaka haha};
print "@rocks";

9.Perl most commonly used default variable: $_
Although it is not the only default variable in Perl, it is undoubtedly the most common use. You'll see in many examples that Perl automatically uses variable $_ when it doesn't require it to use a variable or value, which saves programmers a lot of time thinking about which variable to use.
Copy Code code as follows:

$_ = "Yahoo google Baidu";
Print

10.reverse operation
The reverse (reverse) operation returns the list of inputs (possibly arrays) in reverse order.
Copy Code code as follows:

@fred = 6..10;
@barney = reverse (@fred);
print "@barney";

Note:reverse returns a list of reverses, and it does not change the value of its arguments. If the return value is not assigned to a variable, then the operation is meaningless.





11.sort operation
the sort operation sorts the list of inputs, possibly arrays, according to the internal character order.


Copy Code code as follows:

@rocks = Qw/bedrock slate rubble granite/;
@sorted = sort (@rocks);
print "@sorted";

12. Scalar and list contexts
Note: A given expression has a different meaning in different contexts (contexts).





Context refers to where an expression exists. When Perl parses an expression, it usually expects a scalar value or a list value. This is called both the context of an expression.





Copy Code code as follows:

@people = QW (Fred Barney Betty);
@sorted = sort @people;
$number = + @people;


Print "@sorted"; #listtexttext: Barney, Betty, Fred.
Print "\ n";
Print "$number"; #scalar context: 42+3, get 45


13. Using list-producing expressions in scalar context
Copy Code code as follows:

@backwards = Reverse Qw/yabba dabba doo/;
Print "@backwards"; #return doo, Dabba, Yabba.


Print "\ n";
$backwards = Reverse Qw/yabba dabba doo/;
Print "$backwards"; #return oodabbadabbay


14. Use scalar-producing expression in list context
If an expression is not a list value, the scalar value is automatically converted to a list of elements.
Copy Code code as follows:

@fred = 6*7;
@barney = "Hello". ' '. "World";


Print "@fred"; #return 42
Print "@barney"; #return hello World


15. Cast to scalar context
Sometimes a scalar context may be required and Perl expects a list. In this case, you can use the function scalar. It is not a real function because it simply tells Perl to provide a context:
Copy Code code as follows:

@rocks = QW (talc quartz jade Obsidian);
Print "How many rocks does you have?\n";
Print "I have", @rocks, "rocks!\n"; #false, output Rocks's name
Print "I have", scalar @rocks, "rocks!\n"; #correct,output its numbers







Note: No corresponding function can be cast to the list context.




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.