1. Perl
  2. here

Let's understand Perl arrays

An array is a variable that can store multiple values. Use arrays when you need to work with multiple pieces of the same type of data. Perl arrays are useful because they are called dynamic arrays and automatically grow in size.

Array basics

I will explain the basics of arrays.

  • Array declaration
  • Initialize
  • Element reference
  • Assignment to element
  • Number of arrays
  • Iterative processing

Array declaration

Use my to declare an array as you would for a scalar variable. Prefix with @(at sign) to represent the array.

my @numbers;

Array initialization

You can assign data representing multiple values called list to the array. The list is

(Value 1, Value 2, Value 3)

It is expressed using () like.

To assign a list to an array:

@numbers = (10, 25, 40, 4, -6);

You can also declare and assign an array at the same time.

my @numbers = (10, 25, 40, 4, -6);

Array element reference

To reference the elements of an array: Note that the first character is $, not @. Subscripts start at 0.

$Array[subscript]

You can output the first element and the second element as follows:

print $numbers[0];
print $numbers[1];

Array element assignment

To make an assignment:

$Array[subscript] = value

Try substituting 20 for the first element.

$numbers[0] = 20;

Number of elements in the array

To get the number of arrays, evaluate the arrays in a scalar context. I'll explain the scalar context elsewhere, but remember that you can get the number of arrays by assigning an array to a scalar variable at first.

my $cnt = @nums;

See the following article for a detailed explanation of how to get the number of elements in an array.

Process the elements of the array in order

Use a for or foreach statement to process the elements of an array in sequence. For is used when you want to access in order using subscripts, and foreach is used when you simply want to process arrays in order. It's a good practice in Perl to use for when foreach can't handle it.

Let's output the elements of the array in order with for statement.

for (my $i = 0; $i < @nums; $i++) {
  print $nums[$i], "\n";
}

Let's output the elements of the array in order with foreach statement.

foreach my $num (@nums) {
  print $num, "\n";
}

Manipulation of array elements

You can use functions to add and retrieve elements from the array.

  • shift function
  • unshift function
  • pop function
  • push function

shift function

You can use the "shift function" to "get the first element" of an array. If @array was (1, 2, 3), 1 would be assigned to $first and @array would be (2, 3).

my $first = shift @array;

unshift function

You can use the "unshift function" to "add an element to the beginning" of an array. If @array was (1, 2, 3) then @array would be (5, 1, 2, 3).

unshift @array, 5;

pop function

You can use the "pop function" to "extract the last element" of an array. If @array is (1, 2, 3), 3 is assigned to $last and @array becomes (1, 2).

my $last = pop @array;

push function

You can use the "push function" to "add an element to the end" of an array. .. If @array was (1, 2, 3) then @array would be (1, 2, 3, 5).

push @array, 5;

Sorting the array

Use the sort function to sort the array.

sort function

Pass a code block for comparison as the first argument. To sort in ascending order, write $a before $b, and to sort in descending order, write $b before $a. Use <=> as the comparison operator if you want to compare as a number, and use cmp if you want to compare in lexicographical order.

# Sort in ascending order
@sorted = sort {$a operator $b} @array;

# Sort in descending order
@sorted = sort {$b operator $a} @array;

Let's sort the numbers in ascending order. @nums becomes (2, 3, 5, 8).

# Sort by numerical value in ascending order
my @nums = (5, 8, 3, 2);
@nums = sort {$a <=> $b} @nums;

Easily sort in reverse order

You can also use the "reverse function" if you want to easily sort in reverse order.

@reverse = reverse @elements;

Array reference

A reference is the location of the memory that contains the array . If you know C language, think of it as a "pointer that cannot perform address arithmetic". If you know Java, think of it as a "reference".

Creating an array reference

my $numbers_ref1 = \@numbers;

You can create an array reference by prefixing @with \.

Create a direct array reference

my $numbers_ref2 = [1, 2, 3, 4];

Enclose the list in [] to serve as an array reference.

Array element reference

$numbers_ref2->[0]

Array reference->[index]

Comparison of arrays and array reference

I compared the array and the array reference. It's easy to misunderstand, so let's get a better understanding of the difference between the two.

Element reference

# arrangement
$numbers[0]

# Array reference
$numbers_ref->[0]

Array reference dereference

@$numbers_ref

Dereference when you want to return to an array such as for statement or a function that takes an array as an argument

Array reference are also explained in detail on the following pages.

List

A list is a representation of a sequence of multiple values. Lists and arrays are different. Lists are notations, while arrays are variable.

# List
('a', case:

  break; b', 'c', 'd')

Lists can be assigned to arrays.

# Assignment to array
my @array = ('a', 'b', 'c', 'd');

RiSee List-A list of multiple values for more information on strikes.

Functions/syntax/operators related to arrays

splice function

Use the splice function to perform complex operations on array elements . You can retrieve and replace multiple elements. If $length is omitted when fetching multiple elements, the target is from the position of $pos to the end of the array.

# Extraction of multiple elements
@parts = splice @array, $pos, $length;

# Multi-element replacement
splice @array, $pos, $length, @replace;

grep function

You can use the " grep function " to retrieve only the elements that match the conditions in the array. Each element of @array is passed to the default argument $_. Only elements that meet conditional statement will be added to @matched.

# Extract only the elements that match the conditions
@matched = grep {conditional statement} @array;

map function

Use the map function to convert all the elements of a array . Each element of @array is passed to the default variable $_, so perform the necessary conversions in the code block {}. The last evaluated conversion statement is added to @mapped in order.

# Conversion of all elements of the array
@mapped = map {conversion} @array;

String list operator

There is an operator called the string list operator to concisely describe a list of strings. You can use the string list operator to represent a list of strings without writing single quotes or commas.

qw(string 1 string 2 string 3)

This is an example of actually using the string list operator.

my @strings = qw/cat dog mouse/;

It has the same meaning as the following list of strings.

my @strings = ('cat', 'dog', 'mouse');

Array slice

To retrieve multiple elements by specifying the index from the array, use a technique called array slice .

# Array slice
my @values = @array['m', 'n', ...]

"Multidimensional data structure" that combines arrays and hashes

Understanding "multidimensional data structures" that combine "arrays", "hashes" and "reference" is essential to becoming an intermediate player.

# Hash array
my $people = [
  {name =>'Kimoto', age => 36},
  {name =>'Tanaka', age => 20}
]

The "multidimensional data structure" is explained in detail in the next article, so please refer to it.

Example program

Search for elements in an array, remove duplicate elements in an array, count duplicates

This is an example to search for elements in an array, remove duplicate elements in an array, and count duplicates.

use strict;
use warnings;

my @numbers = (1, 2, 3, 3, 4, 5, 6, 6, 6, 7, 8);
print'array: @numbers = ('. join(',', @numbers). ")\n\n";

# 1: Check if the array contains the specified element.
# Apply grep.
my $saerch_number = 3;
if (grep {$_ == $saerch_number} @numbers) {
  # If the element to be searched is found, the inside of if statement will be true.
  print "1: $saerch_number exists.\n";
}

# 2: Remove duplicates from array (order is not guaranteed)
# The hash key has the property of not allowing duplication.
my %no_duplicate_hash;
for my $number (@numbers) {
  $no_duplicate_hash{$number}++;
}

# Get a list of hash keys
my @no_duplicate_numbers = keys %no_duplicate_hash;
print '2: @no_duplicate_numbers = ('. join(',', @no_duplicate_numbers). ")\n\n";

# 3: Count the number of overlapping elements in the array (continued above)
print "3: Number of elements\n";
for my $key (sort keys %no_duplicate_hash) {
  print "$key contains $no_duplicate_hash{$key}.\n";
}

Array reference

This is an example program for array reference, array conversion, and element reference.

use strict;
use warnings;

my @numbers = (1, 2, 3, 4, 5, 6, 7, 8);
print "array: \@numbers =", join(',', @numbers). ")\n\n";

# 1: Array reference If you put\before @, it becomes an array reference.
my $numbers_ref1 = \@numbers;

# You can revert to the original array by prefixing the array reference with @.
# This is called a dereference.
print "array: \@\$numbers_ref1 =" .join(',', @$numbers_ref1), ")\n";

# 2: However, I usually don't write it like the above.
# Make a direct array reference using something called an anonymous array ([]).
my $numbers_ref2 = [1, 2, 3, 4];
print "array: \$numbers_ref2 =", join(',', @$numbers_ref2). "]\n\n";

# 3: Access the elements of the array. ($array_ref->[index])
print "\$numbers_ref2->[0] = $numbers_ref2->[0]\n";
print "\$numbers_ref2->[1] = $numbers_ref2->[1]\n";

Output

Array: @numbers = (1,2,3,4,5,6,7,8)

Array: @$numbers_ref1 = (1,2,3,4,5,6,7,8)
Array: $numbers_ref2 = [1,2,3,4]

$numbers_ref2->[0] = 1
$numbers_ref2->[1] = 2

Example of array and array reference comparison

This is an example program that allows you to see how arrays and array reference differ.

use strict;
use warnings;

my @numbers = (1, 2, 3);
print "array: \@numbers =", join(',', @numbers), ")\n\n";

my $numbers_ref = [1, 2, 3];

# 1. Element reference
print "1. Element reference\n";
print "\$numbers[0] =", $numbers[0], "\n";

# Array reference
print "\$numbers_ref->[0] =", $numbers_ref->[0], "\n";
print "\n";

# 2. Processing of each element
print "2. Processing of each element\n";

# arrangement
print "\@numbers =";
for my $number (@numbers) {
  print $number. ", ";
}
print "\n";

# Array reference (dereference it to for statement)
print "\@{\$numbers_ref} =";
for my $number (@$numbers_ref) {
  print $number. ", "
}
print "\n\n";

# 3. How to use the function
print "3. How to use the function\n";

# arrangement
push @numbers, 4;
@numbers = sort {$b <=> $a} @numbers;
print "\@numbers = (", join(',', @numbers), ")\n";

# Array reference (dereference and pass to function)
push @$numbers_ref, 4;

# The sort function returns an array, so use an anonymous array []
# Recreating an array reference.
$numbers_ref = [sort {$b <=> $a} @$numbers_ref];
print "\@\$numbers_ref =", join(',', @$numbers_ref), ")\n\n";

Output

Array: @numbers = (1,2,3)

1. Element reference
$numbers[0] = 1
$numbers_ref->[0] = 1

2. Processing of each element
@numbers = 1,2,3,
@{$numbers_ref} = 1,2,3,

3. How to use the function
@numbers = (4,3,2,1)
@$numbers_ref = (4,3,2,1)

Column "Perl that incorporates dynamic arrays into language features"

Arrays that are built into Perl as a language feature are called dynamic arrays because you can freely add and remove values.

Perl has made a great decision to incorporate dynamic arrays into the language as a language feature. It's a very useful idea to handle arrays freely. This was a huge success, with most later scripting languages incorporating dynamic arrays into their languages.

Perl, a treasure trove of ideas created by linguist Larry Wall, is still alive.

Related Informatrion