天天看点

Perl 数组 操作符 pop,push,shift, unshift,splice

这几个操作符都会改变数组的内容;

1.pop    后端弹出数组的值

2.push    后端压入某个值到数组中

3.shift    前段弹出数组的值

4.unshift    前段插入某个值到数组中

5. splice     可操作数组任意位置的值,(可以在任意位置压入,弹出数组的任意个数的值);

splice 参数:

1.  要操作的数组;

2.  开始的位置

3.  弹出个数  (不是必要参数,如果没有会从开始位置将后面的都弹出,0代表不弹出)

4. 要插入的片段 (不是必要参数,弹出之后 是否还要压入值到数组中)

code:

#!/usr/bin/perl

use strict;

my @g_arr = qw/this is a test about arr/;

#pop  : get and cut the last value ;

my $pop_value = pop @g_arr ;

print $pop_value ."\n";

print "-------------------------------------------\n\n\n";
#push : insert into a value at tail of arr;

push @g_arr , "new_word";

print "push result: ";
for (my $i = 0 ; $i < @g_arr ;$i++){
	print $g_arr[$i]."    ";
}
print "\n-------------------------------------------\n\n\n";

#shift : get and cut the first value

my $shift_value = shift @g_arr ;
print $shift_value."\n";
print "-------------------------------------------\n\n\n";

#unshift : insert into the value at head of arr;

unshift  @g_arr ,"new_shift";

print  "unshift  result : ";
for (my $i = 0 ; $i < @g_arr ;$i++){
	print $g_arr[$i]."   ";
}
print "\n-------------------------------------------\n\n\n";


#splice : get and cut a value  at any postion of array ;
#param :
#	1. array;
#	2.start positon;
#	3.length; not must,default:max
#	4.switch data; not must;

@g_arr = qw/this is a test about arr/;
my @tmp_arr = splice @g_arr,1;

print "tmp_arr : ";
for(my $i = 0; $i < @tmp_arr ;$i++){
	print $tmp_arr[$i]."   ";
}
print "\n========================\n";
print "g_arr : ";
for (my $i = 0; $i < @g_arr ;$i ++ ){
		print $g_arr[$i]."   ";
}
print "\n========================\n";
#now tmp_arr : is a test about arr;
#    g_arr : this;

@tmp_arr = splice @g_arr ,0,1,qw/this is a test about arr/;
print "tmp_arr : ";
for(my $i = 0; $i < @tmp_arr ;$i++){
	    print $tmp_arr[$i]."   ";
}   
print "\n========================\n";
print "g_arr : ";
for (my $i = 0; $i < @g_arr ;$i ++ ){
	        print $g_arr[$i]."   ";
}
print "\n========================\n";



           

result:

Perl 数组 操作符 pop,push,shift, unshift,splice

另外:reverse  和  sort   也可以对数组操作;但是这两个关键字不会改变数组的内容;

#!/usr/bin/perl5
#
use strict ;

my @g_arr = 1..5;



#reverse   :  reverse the arr

my @r_g_arr = reverse @g_arr;

foreach my $idx (0..$#r_g_arr){
    print "reverse result:  $idx  =  $r_g_arr[$idx] \n";
}

# sort : sort the arr 

my @s_g_arr = sort @r_g_arr;

foreach my $idx (0..$#s_g_arr){
    print "sort result : $idx = $s_g_arr[$idx] \n";
}
           

result:

Perl 数组 操作符 pop,push,shift, unshift,splice