美文网首页
Perl的pop, push, shift, unshift和s

Perl的pop, push, shift, unshift和s

作者: PETJO | 来源:发表于2021-06-13 06:43 被阅读0次

8. pop 和 push 操作符

  • push的第一个参数或者pop的参数必须是数组变量,对列表直接量操作没有意义。
  • pop操作符用于提取数组末尾的元素,并将此作为返回值。
  • 空上下文(void context)中使用 pop操作符,用来删除数组中的最后一个元素。
  • pop处理空数组变量,返回undef。
  • push操作符用于添加元素(一个或一串)到数组尾端。
#pop在数组末尾提取元素
my @array = 1..10;
print "@array\n";

my $fred = pop(@array);
print $fred . "\n";

my $barney = pop @array;
print $barney . "\n";

pop @array;    #空上下文,删除末尾元素
print "@array\n";

#push在数组末尾添加元素
push(@array, 8);
print "@array\n";

push @array, 9;
print "@array\n";

push(@array, 10..15);
print "@array\n";

push @array, 16..19;
print "@array\n";

my @others = qw/ 9 0 2 1 0 /;
push @array, @others;
print "@array\n";

9. shift和unshift操作符

  • 对数组的开头进行操作。
  • shift处理空数组变量,返回undef。
my @array = qw/ dino fred barney /;
print "@array\n";

my $m = shift (@array);
print "$m\n";
my $n = shift @array;
print "$n\n";

shift @array;
print "@array\n";

my $o = shift @array;    #$o变成undef,@array还是空的
print "$o\n";

unshift(@array, 5);
print "@array\n";

unshift @array, 4;
print "@array\n";

my @others = 1..3;
unshift @array, @others;
print "@array\n";

10. splice操作符

  • splice用于在数组中间移除或添加元素,splice最多接受4个参数,最后两个参数是可选的。
  • 第一个参数:splice要操作的数组;
  • 第二个参数:splice要操作的一组元素的开始位置(数组索引位置);
  • 第三个参数:splice要操作的元素的个数(长度);
  • 第四个参数:splice要替换的列表。
  • 实际上,添加新元素列表不需要预先删除某些元素,把表示长度的第三个参数设为0,即可不加删除地插入新列表。

my @array = qw/ pebbles dino fred barney betty /;
print "@array\n";
my @removed_array = splice @array, 2;
print "@removed_array\n";
print "@array\n";

my @array = qw/ pebbles dino fred barney betty /;
print "@array\n";
my @removed_array = splice @array, 2, 2;
print "@removed_array\n";
print "@array\n";

my @array = qw/ pebbles dino fred barney betty /;
print "@array\n";
my @removed_array = splice @array, 2, 2, qw(wilma honey);
print "@removed_array\n";
print "@array\n";

# 长度为0,仅添加元素
my @array = qw/ pebbles dino fred barney betty /;
print "@array\n";
my @removed_array = splice @array, 2, 0, qw(wilma);
print "@removed_array\n";
print "@array\n";

相关文章

网友评论

      本文标题:Perl的pop, push, shift, unshift和s

      本文链接:https://www.haomeiwen.com/subject/epuweltx.html