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);
I know that there are only 3 values present in the array (i.e in this case 1,2 and 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
? [i.e. with the help of flip-flop operator?]
Thanks, 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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With