PERL刪除數組元素的多種方法

好比說: @array = ('ray', 'loca', 'simon', 'ray');
這裏,咱們想刪除‘ray’這個元素。

列出幾種方法:
1. 用grep函數。

函數名 grep
調用語法 @foundlist = grep (pattern, @searchlist);
解說 與同名的UNIX查找工具相似,grep函數在列表中抽取與指定模式匹配的元素,參數pattern爲欲查找的模式,返回值是匹配元素的列表。
例子 @list = ("This", "is", "a", "test");
@foundlist = grep(/^[tT]/, @list);
結果 @foundlist = ("This", "test");

2. 用map函數

函數名 map
調用語法 @resultlist = map (expr, @list);
解說 此函數在Perl5中定義,能夠把列表中的各個元素做爲表達式expr的操做數進行運算,其自己不改變,結果做爲返回值。在表達式expr中,系統變量$_表明各個元素。
例子 一、@list = (100, 200, 300);
@results = map ($_+1, @list);
二、@results = map (&mysub($_), @list);
結果 一、(101, 201, 301)
二、無

3. 用splice或者delete

函數名 splice
調用語法 @retval = splice (@array , slipelements, length, @newlist);
解說 拼 接函數能夠向列表(數組)中間插入元素、刪除子列表或替換子列表。參數skipelements是拼接前跳過的元素數目,length是被替換的元素 數,newlist是將要拼接進來的列表。當newlist的長度大於length時,後面的元素自動後移,反之則向前縮進。所以,當length=0 時,就至關於向列表中插入元素,而形如語句
splice (@array , -1, 0, "Hello");
則向數組末尾添加元素。而當newlist爲空時就至關於刪除子列表,這時,若是length爲空,就從第skipelements個元素後所有刪除,而刪除最後一個元素則爲:splice (@array , -1);這種狀況下,返回值爲被刪去的元素列表

二者均可以按照index直接刪除array或者hash的元素。可是delete刪除元素後, index後面的元素並不會
主動往前移動,該元素刪除後,在array還留有一個undef的元素,顯然刪除得不夠乾淨。

下面用個小程序說明具體操做:

程序:

#!/usr/bin/perl


use strict;
use warnings;

my @array = ('ray', 'loca', 'simon', 'ray');
my $wanted = 'ray';

print "***show howto delete elements from array***\n\n";
print "Old array is \'@array\"\n";

# Method One: using grep

@array = grep { $_ ne "$wanted" } @array;
print "Now array is \"@array\"\n";

# Method Two: using map

@array = ('ray', 'loca', 'simon', 'ray');
# Function: if the the input string isn't the wanted string
# return the input string.
sub my_print
{
my ( $input, $wanted ) = @_;
return $input if ( $input ne $wanted );
}
@array = map { my_print($_, "$wanted") } @array;
print "Now array is \"@array\"\n";

# Method Three: using splice or delete
@array = ('ray', 'loca', 'simon', 'ray');
# The position of first "ray" is 0
splice (@array, 0, 1);
print "Now array is \"@array\"\n";
# The position of first "ray" is 2

splice @array, 2, 1;
print "Now array is \"@array\"\n";
小程序


程序運行結果爲:

[ray@localhost perl]$ ./array_ops.pl
***show howto delete elements from array***

Old array is 'ray loca simon ray"
Now array is "loca simon"
Now array is " loca simon "
Now array is "loca simon ray"
Now array is "loca simon" 數組

1 grep, 好比
@a=(1,2,3,4,5);
@a=grep(/[^3]/,@a);
print "@a\n";

結果爲1 2 4 5;

2 splice, 好比
@a=(1,2,3,4,5);
splice( @a ,2,1);
print "@a\n";

結果爲1 2 4 5

splice也能夠往數組中某位置添加數據,好比
@a=(1,2,3,4,5);
@b=(999);
splice( @a ,2,0,@b); #這個0是確保添加元素用的 print "@a\n"; 結果爲1 2 999 3 4 5 不要試圖使用$a[2]=""或者$a[2]=undef來清空數組中的某個元素。
相關文章
相關標籤/搜索