【发布时间】:2010-11-22 10:25:52
【问题描述】:
我有一个要求,我需要在循环内执行一个语句,以便第一次出现变量。
例如:
给定数组我的@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。在触发器运算符的帮助下?]
谢谢, 兰吉特
【问题讨论】: