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
source share