- Perl 6 Deep Dive
- Andrew Shitov
- 480字
- 2021-07-03 00:05:48
Methods of the Array type
An array in Perl 6 is actually an object of the Array class. Working with classes is a subject of Chapter 8, Object-Oriented Programming. So far, we will discuss how we can access different properties of arrays in Perl 6 programs.
To get the length of an array, call the elems method, as follows:
my @a = 1, 3, 5;
say @a.elems; # 3
The three methods—push, pop, and append—modify the array: push adds a new element to the end of the array; pop takes the last element, removes it from the array, and returns it; append adds new elements to the end and, unlike push, can add more than one new element. Let's examine the output of the following program:
my @a = 1, 3, 5;
@a.push(7);
say @a; # [1 3 5 7]
say @a.pop; # 7
say @a; # [1 3 5]
my @b = 9, 11;
@a.append(@b);
say @a; # [1 3 5 9 11]
Alternatively, you may use functions instead of methods. The preceding program can be written differently, as shown here:
my @a = 1, 3, 5;
push @a, 7;
say @a; # [1 3 5 7]
say pop @a; # 7
say @a; # [1 3 5]
my @b = 9, 11;
append @a, @b;
say @a; # [1 3 5 9 11]
The next group, unshift, shift, and prepend, are the three methods complementary to push, pop, and append. The method unshift adds an element to the beginning of an array; shift removes and returns the first element; prepend adds new elements to the beginning. The following block of code demonstrates the effect of using these methods:
my @a = 1, 3, 5;
@a.unshift(7);
say @a; # [7 1 3 5]
say @a.shift; # 7
say @a; # [1 3 5]
my @b = 9, 11;
@a.prepend(@b);
say @a; # [9 11 1 3 5]
The splice method cuts the array into three parts and optionally replaces the middle one with a new list. The first two arguments of the splice method are the index of the first element that will be removed or replaced and the length of that fragment. For example, consider the following piece of code:
my @even = 2, 4, 6, 8, 10, 12, 14, 16, 18, 20;
@even.splice(4, 3);
say @even; # [2 4 6 8 16 18 20]
Here, three elements with indices 4, 5, and 6 will be removed from the original array.
In the next example, the same elements are replaced with the values 100 and 200:
my @even = 2, 4, 6, 8, 10, 12, 14, 16, 18, 20;
@even.splice(4, 3, (100, 200));
say @even; # [2 4 6 8 100 200 16 18 20]
The length of the replacement does not need to be the same as the removed part.
- Vue.js 3.x快速入門
- 計(jì)算機(jī)圖形學(xué)編程(使用OpenGL和C++)(第2版)
- C語言程序設(shè)計(jì)基礎(chǔ)與實(shí)驗(yàn)指導(dǎo)
- Python編程完全入門教程
- 深入淺出Serverless:技術(shù)原理與應(yīng)用實(shí)踐
- Visual FoxPro程序設(shè)計(jì)
- R語言與網(wǎng)絡(luò)輿情處理
- INSTANT Sinatra Starter
- Learning jQuery(Fourth Edition)
- Web性能實(shí)戰(zhàn)
- Emotional Intelligence for IT Professionals
- SEO教程:搜索引擎優(yōu)化入門與進(jìn)階(第3版)
- OpenCV 3.0 Computer Vision with Java
- Functional Python Programming
- Java EE實(shí)用教程