我使用push
函數將值存儲在數組中。數組中的第一個值被存儲在4個元素而不是第一個元素。例如,當我打印第一個元素$array[1]
時存儲值後,它會打印空格/什麼都沒有,但是當我打印第四個元素$array[4]
時,它會打印第一個值。有關如何在數組開頭刪除不需要的值的任何建議?如何從Perl數組的開頭刪除不需要的值?
0
A
回答
2
while (value_meets_shubster_s_definition_of_crap($array[0])) {
shift @array;
}
sub value_meets_shubster_s_definition_of_crap {
my $value = shift;
&helip;
return true or false;
}
…但最好避免將「垃圾」值放在陣列上。
0
如果你想消除所有不需要的值:
@array = grep { not value_meets_shubster_s_definition_of_crap($_) } @array;
然而,正如戴維·多沃德指出,這消除不需要的值從數組中間爲好。要在開始擺脫只有值,則可以使用first_index
從List::MoreUtils這可能是比shift
個循環更有效:
#!/usr/bin/perl
use strict;
use warnings;
use List::MoreUtils qw(first_index);
my @array = (0, 1, 0, 2);
my $begin = first_index { not is_unwanted($_) } @array;
@array = @array[ $begin .. $#array ];
print "@array\n";
sub is_unwanted {
my ($v) = @_;
return if $v;
return 1;
}
__END__
輸出:
C:Temp> yjk
1 0 2
更新:我預感,似乎一直是錯的:
#!/usr/bin/perl
use strict;
use warnings;
use Benchmark qw(cmpthese);
use List::MoreUtils qw(first_index);
my @array = (0, 1, 0, 2, 3, 4, 5, 6, 7, 8, 9);
cmpthese -10, {
'first_index' => \&using_first_index,
'shift' => \&using_shift,
'nop' => \&nop,
};
sub using_first_index {
my @result = @array;
my $begin = first_index { not is_unwanted($_) } @result;
@result = @result[ $begin .. $#result ];
}
sub using_shift {
my @result = @array;
shift @result while is_unwanted($result[0]);
}
sub nop { my @result = @array; }
sub is_unwanted {
my ($v) = @_;
return if $v;
return 1;
}
結果:
Rate first_index shift nop
first_index 75767/s -- -71% -89%
shift 258810/s 242% -- -61%
nop 664021/s 776% 157% --
4
您可以使用'shift'運算符從陣列的前部移除元素。
但我認爲這個問題比這個更深,而你卻以錯誤的方式看待它。如果您在數組中存儲未知的'不想要的'值,您需要找出發生的地點和原因並防止它發生,而不是繞過這些找到您要查找的內容。
2
你是如何創建數組?使用我的驚人的ESP的力量,我猜測你有一個split
的地方,保持領先的空場地。如果我錯了,你必須告訴我們更多關於你在做什麼。
這裏有一點XY的問題。您在問我們如何實施您已經選擇的解決方案,而不是讓我們真正解決問題。
相關問題
- 1. 如何從數組中刪除不需要的東西?
- 2. 如何從此JSON數組中刪除不需要的元素?
- 3. 如何從Perl中的數組中刪除隨機值?
- 4. 如何從文件的開頭刪除??
- 5. 如何從sql表中刪除不需要的行值?
- 6. 刪除數組開頭的重複項
- 7. 從數組的尾部刪除不需要的元素?
- 8. 如何在刪除perl中不需要的行後刪除空行?
- 9. 如何刪除不需要的字符
- 10. 如何刪除不需要的ID?
- 11. 如何刪除不需要的favicon
- 12. 如何從多維數組中刪除不必要的行?
- 13. 如何從數組中刪除空值?
- 14. 如何從Perl數組中刪除重複的項目?
- 15. 如何從Perl哈希中刪除空的數組/參考?
- 16. 如何從Perl中的字符串開頭刪除字符序列列表?
- 17. 刪除不需要的參數
- 18. 需要在foreach中刪除數組中的重複值
- 19. 如何從cookie數組中刪除數組中的值?
- 20. Ruby中的散列數組 - 刪除不需要的內容
- 21. 需要刪除空值
- 22. 如何從接口中刪除不需要的功能
- 23. 如何從xslt輸出xml中刪除不需要的空xmlns
- 24. 如何使用Nokogiri從HTML中刪除不需要的標籤?
- 25. 如何從jboss日誌中刪除不需要的行?
- 26. 如何從myapps.developer.ubuntu.com中刪除不需要的捕捉包?
- 27. 從數組中刪除值
- 28. 從數組中刪除值?
- 29. 從數組中刪除值
- 30. 如何刪除數組中的double值?
你在推動你的陣列?這可能是問題所在。聽起來就像你在推動另一個數組而不是推動標量。順便說一下,第一個元素位於索引0,而不是1。 – jeje 2009-07-10 17:20:28
@ jeje:匹配正則表達式後,我正在推入值。像這樣:push(@value,join(「」,$ file =〜/ $ find /)) – shubster 2009-07-10 17:46:23
@shubster好的,所以你在你的數組@value中推入一個數組(顯然是5個元素)。 – jeje 2009-07-10 18:02:11