Flip flop operator in perl

I have a requirement when I need to execute a statement inside a loop for the first occurrence of a variable.

For example: This array is my @rand_numbers = qw(1 2 1 2 3 1 3 2);
I know that only 3 values ​​are present in the array (i.e., in this case, 1,2 and 3)
I want to print something (or do something) at the first collision of each value (only in the first meeting and never repeat it for a sequential meeting of the corresponding value).

Below 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 the above result without a variable like $came_across_x ? [Those. using a flip flop operator?]

Thanks Ranjith

+4
source share
2 answers

This may not work for your real 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" } 
+11
source

Just use the hash as @Chris suggests.

Using a flip-flop operator seems impractical here because you still need to keep track of visible variables:

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

All Articles