天天看點

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