简体   繁体   English

perl三元语句与print有奇怪的结果

[英]perl ternary statement has odd results with print

I've been messing around with writing FizzBuzz in perl...to be specific I want to make a nightmare looking line of code just to see if I can do it. 我一直在搞乱在Perl中编写FizzBu​​zz ...具体来说我想做一个噩梦看代码行只是为了看看我是否可以做到。 This means nested ternary statements of course! 这意味着嵌套的三元语句!

However I'm finding that on the 15's it never prints FizzBuzz, just Fizz. 但是我发现在15年代它从未打印过FizzBu​​zz,只是Fizz。 I cannot find a reason because that implies that if the first ternary statement returns true it's just skipping the second statement. 我找不到原因,因为这意味着如果第一个三元语句返回true,它只是跳过第二个语句。

Here's the little nightmare I've come up with. 这是我想出的小噩梦。 Yes it can be way worse, but I'm really not that strong with perl and this is just an exercise for myself: 是的,它可能会更糟,但我真的不是那么强大的perl,这只是我自己的练习:

#!/usr/bin/perl

for (my $i=1; $i<=100; $i++) {
      ( !( ($i % 3 == 0) ? print "Fizz" : 0) && !( ($i % 5 == 0) ? print "Buzz" : 0) ) ? print "$i\n" : print "\n";
}

Here's the first 20 lines of output: 这是前20行输出:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
Fizz
16
17
Fizz
19
Buzz

What would the print statement be doing that would cause this to happen? print语句会做什么会导致这种情况发生?

This is an example of short-circuit evaluation, as documented in perlop . 这是perlop中记录的短路评估示例 In cases of a() && b() , b() will never be evaluated if a() is false. a() && b()情况下,如果a()为false,则永远不会计算b() In your (deeply nested and confusing) ternary statement, that amounts to the same thing. 在你的(深层嵌套和令人困惑的)三元语句中,这相当于同样的事情。 To fix this I'd split the statement up into multiple lines. 为了解决这个问题,我将声明拆分为多行。

Simplified: 简化:

for my $i ( 1 .. 20 ) {
    print +( ( $i % 3 ? '' : 'Fizz' ) . ( $i % 5 ? '' : 'Buzz' ) ) || $i, "\n";
}

Outputs: 输出:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz

Actually, here we go, bit shifting saves the day 实际上,在这里,我们去,位移节省了一天

#!/usr/bin/perl

for (my $i=1; $i<=100; $i++) {
      (((($i % 3 == 0) ? print "Fizz" : 0) + ( ($i % 5 == 0) ? print "Buzz" : 0)) << 1) ? print "\n" : print "$i\n";
}

Output: 输出:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz

The most klugey solution 最笨的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM