2010-10-29 72 views
7

我是一個Perl新手。我有一個代碼,其中一個變量在foreach循環中加載了多個值。我想要做的只是對該變量執行一些操作,僅在該變量中包含該變量。什麼是最有效的方式在perl中這樣做,因爲我正在處理的數據非常大。Perl:查找一個變量的值是否與數組匹配

我的問題的一個簡單的例子,說我有水果的數組我想

@fruits_i_like = qw (mango banana apple); 

但是我有一個foreach循環它得到水果的名稱從數據文件中的$水果變量有所有不同類型的水果。我將如何挑選僅存在於我的@fruits_i_like數組中的$ fruit水果的情況?

+1

「大」有多大? – Zaid 2010-10-29 11:38:54

+0

那麼我需要讀的文件大約是50MB。 – sfactor 2010-10-29 11:43:16

+0

@sfactor:那也不算太壞。 – Zaid 2010-10-29 11:54:20

回答

10

您可以使用這樣的哈希:

my %h = map {$_ => 1 } @fruits_i_like; 
if (exists $h{$this_fruit}) { 
    # do stuff 
} 

下面是這種方式比較VS mfontani解決方案

基準
#!/usr/bin/perl 
use warnings; 
use strict; 
use Benchmark qw(:all); 

my @fruits_i_like = qw/mango banana apple/; 
my $this_fruit = 'banana'; 
my %h = map {$_ => 1 } @fruits_i_like; 
my $count = -3; 
my $r = cmpthese($count, { 
    'grep' => sub { 
     if (scalar grep $this_fruit eq $_, @fruits_i_like) { 
      # do stuff 
     } 
    }, 
    'hash' => sub { 
     if (exists $h{$this_fruit}) { 
      # do stuff 
     } 
    }, 
}); 

輸出:

  Rate grep hash 
grep 1074911/s -- -76% 
hash 4392945/s 309% -- 
+1

將'sub {}'更改爲'q {}'並再次運行該基準。子程序調用開銷可能會更改數字太多。 – tchrist 2010-10-29 12:19:19

+3

如果你爲此創建%h,它不應該成爲基準的一部分嗎? – 2010-10-29 12:58:47

+3

@ØyvindSkaar:我不這麼認爲,因爲OP想要多次結果。 %h只創建一次並使用很多次。這與grep解決方案不同,grep爲每種不同的水果完成。 – Toto 2010-10-29 13:46:17

11

的Perl 5.10或更高?

use strict; 
use warnings; 
use 5.10.0; 
my @fruits_i_like = qw/mango banana apple/; 
my $this_fruit = 'banana'; 
if ($this_fruit ~~ \@fruits_i_like) { 
    say "yummy, I like $this_fruit!"; 
} 

之前5.10:

use strict; 
use warnings; 
my @fruits_i_like = qw/mango banana apple/; 
my $this_fruit = 'banana'; 
if (scalar grep $this_fruit eq $_, @fruits_i_like) { 
    print "yummy, I like $this_fruit!\n"; 
} 

的缺點是整個陣列分析通過尋找匹配。這可能不是最佳選擇,在這種情況下,您可以使用List::MoreUtils'any(),一旦匹配值並且不會繼續通過該數組,它將返回true。

use strict; 
use warnings; 
use List::MoreUtils qw/any/; 
my @fruits_i_like = qw/mango banana apple/; 
my $this_fruit = 'banana'; 
if (any { $this_fruit eq $_ } @fruits_i_like) { 
    print "yummy, I like $this_fruit!\n"; 
} 

快樂黑客!

9

這實際上是查找問題。在像%fruits_i_like(它是O(1)與數組的O(n))這樣的散列中查找@fruits_i_like的值會更快。

使用下面的操作轉換數組的哈希:

​​
相關問題