簡體   English   中英

perl中的觸發器操作符

[英]Flip flop operator in perl

我有一個要求,我需要在循環內執行第一次出現變量的語句。

例如:給定數組我的@rand_numbers = qw(1 2 1 2 3 1 3 2);
我知道數組中只有3個值(即在本例中為1,2和3)
我想在每個值的第一次遇到時打印一些東西(或做某事)(僅在第一次遇到時,並且不會在連續遇到相應值時重復它)。

以下是一種方法

my @rand_numbers = qw(1 2 1 2 3 1 3 2); 
my $came_across_1=0, $came_across_2=0, $came_across_3=0;

for my $x(@rand_numbers) { 
    print "First 1\n" and $came_across_1=1 if($x==1 and $came_across_1==0); 
    print "First 2\n" and $came_across_2=1 if($x==2 and $came_across_2==0); 
    print "First 3\n" and $came_across_3=1 if($x==3 and $came_across_3==0); 
    print "Common op for -- $x \n"; 
}

有沒有辦法實現上面的結果沒有像$came_across_x這樣的變量? [即在觸發器操作員的幫助下?]

謝謝,Ranjith

這可能不適用於您的實際情況,但它適用於您的樣本,並可能會給您一個想法:

my %seen;
for my $x (@rand_numbers) {
  print "First $x\n" unless $seen{$x}++;
  print "Common op for -- $x\n"
}

只需使用@Chris建議的哈希。

使用觸發器操作器似乎在這里不實用,因為您無論如何都需要跟蹤看到的變量:

my %seen;
for (@rand_numbers) {
    print "$_\n" if $_ == 1 && !$seen{$_}++ .. $_ == 1;
    print "$_\n" if $_ == 2 && !$seen{$_}++ .. $_ == 2;
    print "$_\n" if $_ == 3 && !$seen{$_}++ .. $_ == 3;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM