Perl 数组 101 - 创建、循环和操作

Perl中的数组包含一个有序值列表,可以使用内置函数访问。它们是最有用的数据结构之一,在Perl编程中经常使用。

创建一个数组

在Perl中,使用符号来标识变量。数组使用@(类似于数组中的'a'),所以格式是:@任何你选择的名称。数组通过分配一个值列表(括号中用逗号分隔的值)来初始化。与更正式的语言不同,Perl数组可以包含数字、字符串、对象和引用的混合。

my @empty_array;

my @another_empty_array = ();

my @numbers = (1, 2, 3, 4, 5);

my @names_start_with_j = ('John', 'Judy', 'Julia', 'James', 'Jennifer');

my @random_collection = (2013, 'keyboard', 'perltricks.com', 30);

查找数组长度/大小

数组的长度(也称为“大小”)是数组中元素数量的计数。要找到数组的长度,请在标量上下文中使用数组。

my @numbers = (1, 2, 3, 4, 5);
my $array_length = @numbers; 
print $array_length;
# 5

直接访问数组元素

数组可以通过多种方式访问:直接访问一个元素、切片一组元素或遍历整个数组,一次访问一个元素。

直接访问数组元素时,使用带有标量符号($)的前置数组名称,而不是(@),以及括号内的元素索引号。数组是零基的,这意味着第一个元素的索引号是0(而不是1!)。

my @names_start_with_j = ('John', 'Judy', 'Julia', 'James', 'Jennifer');
$names_start_with_j[0]; # John
$names_start_with_j[4]; # Jennifer

零基索引的含义是,数组中最后一个元素的索引号等于数组长度减一。

my @numbers = (11, 64, 29, 22, 100);
my $numbers_array_length = @numbers;
my $last_element_index = numbers_array_length - 1;
# therefore ...
print $numbers[$last_element_index]; 
# 100

有关访问数组最后一个元素的更简单方法 - 请参阅我们最近的文章中的示例。

使用 foreach 遍历数组

可以使用 foreach 循环按顺序访问数组元素,每次迭代一个元素。

my @names_start_with_j = ('John', 'Judy', 'Julia', 'James', 'Jennifer');
foreach my $element (@names_start_with_j) {
    print "$element\n";
}
# John
# Judy
# Julia
# James
# Jennifer

遍历数组的其他常用函数是 grepmap

shift、unshift、push 和 pop

Perl数组是动态长度的,这意味着可以根据需要向数组中添加和删除元素。Perl提供了四个函数来完成此操作:shift、unshift、push 和 pop。

shift 从数组中删除并返回第一个元素,减少数组的长度1。

my @compass_points = ('north', 'east', 'south', 'west');
my $direction = shift @compass_points;
print $direction; 
# north

如果没有传递数组给 shift,它将操作 @_. 这使它在子程序和方法中非常有用,其中默认 @_ 包含子程序/方法调用的参数。例如。

print_caller("perltricks");
sub print_caller {
    my $caller_name = shift;
    print $caller_name;
}
# perltricks

其他三个数组函数与 shift 的工作方式类似。 unshift 接收并将新元素插入到数组的开头,增加数组的长度1。push 接收并将新元素插入到数组的末尾,增加数组的长度1。pop 从数组中删除并返回最后一个元素,减少数组的长度1。

my @compass_points = ('north', 'east', 'south', 'west');
my $direction = 'north-east';
unshift @compass_points, $direction;
# @compass_points contains: north-east, north, east, south and west

my $west = pop @compass_points; 
push @compass_points, $new_direction; # put $west back

检查数组是否为空或未定义

检查数组是否为空或已定义的简单方法是,在标量上下文中检查它以获取数组中的元素数量。如果数组为空,它将返回0,Perl也将将其评估为布尔值假。请注意,这并不完全等同于未定义,因为可能有一个空数组。

my @empty_array;
if (@empty_array) {
    # do something - will not be reached if the array has 0 elements
}


本文最初发布在 PerlTricks.com

标签

David Farrell

David 是一名职业程序员,他经常 推文博客 关于代码和编程艺术。

浏览他们的文章

反馈

这篇文章有问题?请帮助我们通过在GitHub上打开一个issue或pull request来解决。