Learning notes on lists and arrays in Perl

Time:2021-12-9

1、 List

A list is a sequence of values contained in parentheses, which can be any value or empty, such as: (1, 5.3, “hello”, 2), empty list: ().
Note: a list containing only one value (e.g. (43.2)) is different from the value itself (i.e. 43.2), but they can be transformed or assigned to each other. List example:

Copy codeThe code is as follows:

    (17, $var, “a string”)
    (17, 26 << 2)
    (17, $var1 + $var2)
($value, “The answer is $value”)


2、 Array — storage of list

 

The list is stored in the array variable. Unlike the simple variable, the array variable starts with the character “@”, such as:

Copy codeThe code is as follows:

    @array = (1, 2, 3);


Note:
  (1) Array variable was created with an empty initial value. List: ().
  (2) Because Perl uses @ and $to distinguish group variables and simple variables, the same name can be used for both array variables and simple variables, such as:
 

Copy codeThe code is as follows:

     $var = 1;
     @var = (11, 27.1 , “a string”);


But this is easy to be confused, so it is not recommended.

 

1. Array access

The values in the array are accessed by subscript, and the subscript of the first element is 0. If you try to access an array element that does not exist, the result is null. However, if you assign a value to an element that exceeds the size of the array, the array will grow automatically, and the original element value that did not exist is null. For example:

Copy codeThe code is 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)


Inter array copy

Copy codeThe code is as follows:

     @result = @original;


  Assign a value to a list with an array

Copy codeThe code is as follows:

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


  Array assignment to simple variables
 
     (1) @array = (5, 7, 11);
 

Copy codeThe code is as follows:

      ($var1, $var2) = @array; # $ VAR1 = 5, $var2 = 7, 11 ignored
  


     (2) @array = (5, 7);
 

Copy codeThe code is as follows:

      ($var1, $var2, $var3) = @array; # $var1 = 5, $var2 = 7, $var3 =”” (null)


Assign a value to a variable from standard input (stdin)

Copy codeThe code is as follows:

     $var = ;
     @ array = ; # ^ D is the symbol to end the input


2. Square brackets and variable substitution in strings

Copy codeThe code is as follows:

    ‘$var [0]’ is the first element of array @ var.
    ‘$var \ [0]’ escapes the character ‘[‘, which is equivalent to ‘$var’. ‘[0]’, $VaR is replaced by a variable, and [0] remains unchanged.
    “${var} [0]” is also equivalent to “$var”. “[0]”.
    “$\ {var}” cancels the variable replacement function of braces, including the text: ${var}


3. List range:

Copy codeThe code is 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 codeThe code is as follows:

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


  . For string
 

Copy codeThe code is as follows:

    (“aaa”..”aad”) = (“aaa”,”aab”, “aac”, “aad”)
    @day_of_month = (“01”..”31″)


  . Can contain variables or expressions
 

Copy codeThe code is as follows:

    ($var1..$var2+5)


  . Tips:
 

Copy codeThe code is as follows:

    $fred = “Fred”;
    print ((“Hello, ” . $fred . “!\n”) x 2);


  The results are:
 

Copy codeThe code is as follows:

    Hello, Fred!
    Hello, Fred!


4. Output of array:
(1) @array = (1, 2, 3);

Copy codeThe code is as follows:

    print (@array, “\n”);


  The result is: 123
(2) @array = (1, 2, 3);

Copy codeThe code is as follows:

    print (“@array\n”);


  The results are: 1 2 3
5. Length of list / array
When an array variable appears where a simple variable is expected, the Perl interpreter takes its length.
  

Copy codeThe code is as follows:
@array = (1, 2, 3);
    $ scalar = @array; # $ Scalar = 3, i.e. the length of @ array
    ($scalar) = @array; # $ Scalar = 1, which is the value of the first element of @ array


  Note: Taking the length of the array as the number of cycles, you can program as follows:
   

Copy codeThe code is as follows:
$count = 1;
    while ($count <= @array) {
    print (“element $count: $array[$count-1]\n”);
    $count++;
    }


6. Subarray
  

Copy codeThe code is 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 swap elements as subarrays:
   

Copy codeThe code is as follows:
@array[1,2] = @array[2,1];


7. Library functions for arrays
(1) Sort — sort by character
  

Copy codeThe code is as follows:
@array = (“this”, “is”, “a”,”test”);
    @array2 = sort(@array); # @array2 = (“a”,”is”, “test”, “this”)
    @array = (70, 100, 8);
    @array = sort(@array); # @array = (100, 70, 8) now


(2) reverse — reverse array

Copy codeThe code is as follows:

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


(3) Chop — array tailing
    The meaning of chop is to remove the newline character, the last character when stdin (keyboard) enters a string. If it acts on an array, it does so for each element in the array.
   

Copy codeThe code is as follows:
@list = (“rabbit”, “12345”,”quartz”);
    chop (@list); # @list = (“rabbi”, “1234”,”quart”) now


(4) join / split — connect / split
    The first parameter of join is the intermediate character used for connection, and the rest are the character array to be connected.
  

Copy codeThe code is 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 scalars are regarded as singular numbers in Perl, lists and arrays can be regarded as plural numbers in Perl.

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

Each element in the list is an independent scalar value. These values are sequential, that is, they have a fixed sequence from the beginning to the last element. The elements in the array or list are numbered, and their indexes start from the integer 0 and increase one in turn. Therefore, the index of the first element of the array or list is 0.

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

Lists and arrays can contain any number of elements. It contains at least 0 elements and can fill up your available memory at most. This also reflects Perl’s design philosophy, “there are no unnecessary restrictions”.

1. Access array elements
In Perl, you can access elements through index values, such as: $array [0] = “test”; print $array[0];

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

2. Special array index
If you store an element after the last element of the array, the array will grow automatically. Perl has no length limit, 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. For example, the index of the last element of an array is $#array

A simple way: the negative index value of the array starts from the last element. But don’t think these indexes are circular. If the array has 3 elements, the valid negative index values are – 1 (the last element), – 2 (the middle element), – 3 (the first element). In fact, few people use negative index values other than – 1.

3. List
An array is a list enclosed in parentheses and its elements are separated by commas. These values form the elements of the array.

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

4.qw abbreviation
Practice shows that the list of strings is often used in Perl. A simple way to achieve similar functions without entering a large number of quotation marks is to use QW.

QW means “quoted words” or “quoted by whitespace.” regardless of the interpretation, Perl treats them as single quote strings. You can’t use \ N and $Fred in QW like double quotes. Whitespace (spaces, such as spaces, tabs, newlines and other strings) will be ignored, and the remaining elements form the list.

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

Note: Perl allows any punctuation as a QW list delimiter.

5. List assignment
Like scalar values, list values can also be assigned to variables:

Copy codeThe code is as follows:

($fred[0], $fred[1], $fred[2]) = (”haha”, “wawa”, undef);
print $fred[0].$fred[1].$fred[2];


Each variable in the left list gets a new value, which is the same as the result obtained by using three assignment statements. Since the list has been established before assignment, the following simple method can be used in Perl to exchange the values of two variables.

 

Note: Perl has a simple way to write when you want to reference this array. Add @ (without brackets) before the array name to refer to the entire array.

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

Copy codeThe code is as follows:

@array = 5..9;
pop @array;
foreach $t (@array) {
print $t;
}


You can use or not use parentheses after pop. This is a general rule in Perl: if the meaning of parentheses is unchanged, parentheses are optional.

 

The opposite operation to pop is push, which can add an element (or a column of elements) to the end of the array:

Copy codeThe code is as follows:

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


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

 

7. Shift and unshift operations

Push and pop operate on the end of the array. Accordingly, unshift and shift operate on the beginning of an array (the element with the smallest subscript at the left end of the array).

8. Insert array into string
Like scalars, arrays can be inserted into double quoted strings. The inserted array elements are automatically separated by spaces.

Copy codeThe code is as follows:

@rocks = qw{wawa kaka haha};
print “@rocks”;


9. Default variables most commonly used by Perl:$_
Although it is not the only default variable in Perl, it is undoubtedly the most commonly used. You will see in many examples that Perl automatically uses the variable $when it is not required to use a variable or value, This will save programmers a lot of time thinking about which variable to use.

Copy codeThe code is as follows:

$_ =”yahoo google baidu”;
print;


10. Reverse operation
The reverse operation returns a list of inputs (possibly an array) in reverse order.

Copy codeThe code is as follows:

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


Note: reverse returns a list of reversals that do not change the value of its parameters. If the return value is not assigned to a variable, the operation is meaningless

 

11. Sort operation
The sort operation sorts the input list (possibly an array) according to the internal character order.

Copy codeThe code is as follows:

@rocks = qw/ bedrock slate rubble granite /;
@sorted = sort(@rocks);
print “@sorted”;


12. Scalar and list context
Note: a given expression has different meanings in different 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 the context of the expression.

 

Copy codeThe code is as follows:


@people = qw( fred barney betty );
@sorted = sort @people;
$number = 42 + @people;

 

print “@sorted”;# List context: Barney, Betty, Fred
print “\n”;
print “$number”;# Scalar context: 42 + 3, get 45


13. Use list producing expression in scalar context

Copy codeThe code is as follows:


@backwards = reverse qw / yabba dabba doo /;
print “@backwards”; # Return to Doo, dabba, Yabba

 

print “\n”;
$backwards = reverse qw/ yabba dabba doo /;
print “$backwards”; # Return to oodabbadbbay


14. Use scalar producing expression in the list context
If an expression is not a list value, the scalar value is automatically converted to a list of elements.

Copy codeThe code is as follows:


@fred = 6*7;
@barney = “hello”.’ ‘. “world”;

 

print “@fred”; # Return 42
print “@barney”; # Return to 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 only tells Perl to provide a context:

Copy codeThe code is as follows:

@rocks = qw(talc quartz jade obsidian);
print “How many rocks do you have?\n”;
print “I have “, @rocks, “rocks!\n”; # Error, output the name of rocks
print “I have “, scalar @rocks, “rocks!\n”; # Correct, output its number


Note: no corresponding function can be forcibly converted to list context.