[Munich-pm] Logic short circuit und Unterschied || vs or
Robert C. Helling
helling at atdotde.de
Di Apr 15 22:23:03 PDT 2014
Hallo,
hier noch eine Mail im Nachgang zum heutigen Treffen. In der Tat machen sowohl ‘||' als auch ‘or’ das gleiche logic short circuit (was die Ausführung angehen) und unterscheiden sich nur in ihrer Bindungsstaerke. Dazu ein kleiner Test
#!/usr/bin/env perl
sub a {
my $n = shift;
print "a says $n\n";
return $n;
}
sub b {
my $n = shift;
print "b says $n\n";
return $n
}
sub c {
my ($a, $b) = @_;
return $a || $b;
}
a(1) or b(2);
a(3) || b(4);
2<3 || b(5);
a(6) || 2<3;
2<3 or b(7);
a(8) or 2<3;
c(a(9), b(10));
__OUTPUT__
th-nb-tmpmbp01:or Robert.Helling$ ./test1.pl
a says 1
a says 3
a says 6
a says 8
a says 9
b says 10
Es wird also immer von links nach rechts ausgewertet, auch wenn der Compiler schon sehen könnte, dass das zweite Argument den Ausdruck schon wahr macht (muss auch so sein, denn || hat als Wert den linken Wert, wenn dieser nicht false ist).
So sieht das auch man perlop:
C-style Logical Or
Binary "||" performs a short-circuit logical OR operation. That is, if the left operand is
true, the right operand is not even evaluated. Scalar or list context propagates down to the
right operand if it is evaluated.
[…]
As alternatives to "&&" and "||" when used for control flow, Perl provides the "and" and "or"
operators (see below). The short-circuit behavior is identical. The precedence of "and" and
"or" is much lower, however, so that you can safely use them after a list operator without the
need for parentheses
Und wer meinen Vortrag beim 30c3 anschauen will, kann das hier tun:
https://www.youtube.com/watch?v=3vM5u3VT_WE
Viele Grüße
Robert
--
.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oO
Robert C. Helling Elite Master Course Theoretical and Mathematical Physics
Scientific Coordinator
Ludwig Maximilians Universitaet Muenchen, Dept. Physik
print "Just another Phone: +49 89 2180-4523 Theresienstr. 39, rm. B339
stupid .sig\n"; http://www.atdotde.de
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 495 bytes
Desc: Message signed with OpenPGP using GPGMail
URL: <http://mail.pm.org/pipermail/munich-pm/attachments/20140416/7001613f/attachment.bin>
Mehr Informationen über die Mailingliste Munich-pm