我发现这个非常有用的单行,它可以工作,但我无法理解它是如何设法在文件行中循环两次。
perl6 -ne 'state %l; .say if ++%l{$_} == 1' input-file.txt
Run Code Online (Sandbox Code Playgroud)
只有一个循环。
它将所有行收集为 中的键%l,值是它看到它的次数。
如果这是第一次 ( … == 1),它会打印当前行的副本。
它的工作原理与以下基本相同:
my %l;
for $*ARGFILES.lines() { # this is basically what `-n` does
++%l{ $_ }; # update the count
.say if %l{ $_ } == 1; # print it if this is the first time it was seen
}
Run Code Online (Sandbox Code Playgroud)
我认为… if ++$… == 1使用而不是的原因… unless $…++是它的&prefix:«++»性能略高于&postfix:«++»
另一种可能更有效(取决于 的实现.unique)的编写方式是:
perl6 -e '.put for $*ARGFILES.lines.unique' input-file.txt
Run Code Online (Sandbox Code Playgroud)