我有一个要求,我需要在第一次出现变量时在循环内执行一条语句。
例如:
给定数组我的 @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
这样的变量的情况下实现上述结果? [IE。在触发器运算符的帮助下?]谢谢,
兰吉斯
最佳答案
这可能不适用于您的实际情况,但它适用于您的样本,并且可能会给您一个想法:
my %seen;
for my $x (@rand_numbers) {
print "First $x\n" unless $seen{$x}++;
print "Common op for -- $x\n"
}
关于perl - perl 中的触发器运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4244416/