简体   繁体   English

perl中的触发器操作符

[英]Flip flop operator in perl

I have a requirement where I need to execute a statement inside the loop for the first occurrence of a variable. 我有一个要求,我需要在循环内执行第一次出现变量的语句。

For example: Given array my @rand_numbers = qw(1 2 1 2 3 1 3 2); 例如:给定数组我的@rand_numbers = qw(1 2 1 2 3 1 3 2);
I know that there are only 3 values present in the array (ie in this case 1,2 and 3) 我知道数组中只有3个值(即在本例中为1,2和3)
I want to print something (or do something) on the first encounter of each value(only in the first encounter and never repeat it for the consecutive encounter of the corresponding value). 我想在每个值的第一次遇到时打印一些东西(或做某事)(仅在第一次遇到时,并且不会在连续遇到相应值时重复它)。

Following is one approach 以下是一种方法

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"; 
}

Is there a way to achieve above result with no variable like $came_across_x ? 有没有办法实现上面的结果没有像$came_across_x这样的变量? [ie with the help of flip-flop operator?] [即在触发器操作员的帮助下?]

Thanks, Ranjith 谢谢,Ranjith

This may not work for your real-life situation, but it works for your sample, and may give you an idea: 这可能不适用于您的实际情况,但它适用于您的样本,并可能会给您一个想法:

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

Simply use a hash as @Chris suggests. 只需使用@Chris建议的哈希。

Using the flip-flop operator seems to be not practical here because you'll need to keep track of seen variables anyway: 使用触发器操作器似乎在这里不实用,因为您无论如何都需要跟踪看到的变量:

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