Conditional structures: Difference between revisions

→‎{{header|Perl}}: improve style, language, formatting
m (added a ;Task: (bold) header, added other whitespace to the task's preamble.)
(→‎{{header|Perl}}: improve style, language, formatting)
Line 3,303:
=={{header|Perl}}==
{{works with|Perl|5}}
 
===if/else===
if ($expression) {
do_something;
};
 
<lang perl>if ($expression) {
# postfix conditional
do_something;
do_something if $expression;
}</lang>
 
<lang perl># postfix conditional
if ($expression) {
do_something if $expression;</lang>
do_something;
 
} else {
<lang perl>if ($expression) {
do_fallback;
do_something;
};
}
} else {
do_fallback;
}</lang>
 
<lang perl>if ($expression1) {
do_something;
}
} elsif ($expression2) {
do_something_different;
}
} else {
do_fallback;
}</lang>
 
if ($expression1) {
do_something;
} elsif ($expression2) {
do_something_different;
} else {
do_fallback;
};
===unless===
 
''unless'' behaves like ''if'', only logically negated. You can use it wherever you can use ''if''. An ''unless'' block can have ''elsif'' and ''else'' blocks, but there is no ''elsunless''.
<code>unless</code> behaves like <code>if</code>, only logically negated.
 
''unless'' behaves like ''if'', only logically negated. You can use it wherever you can use ''<code>if''</code>. An ''<code>unless''</code> block can have ''<code>elsif''</code> and ''<code>else''</code> blocks, but there is no ''<code>elsunless''</code>.
 
===ternary operator===
 
The ternary operator is used as an expression within a statement, rather than as a control flow structure containing one or more statements. It is frequently used in assignment, or sometimes for passing function call arguments that vary depending on some condition.
 
<lang perl>$variable = $expression ? $value_for_true : $value_for_false;</lang>
 
===logical operators===
<code>$condition and do_something</code> is equivalent to <code>$condition ? do_something : $condition</code>.
 
<codelang perl>$condition orand do_something</code>; is# equivalent to <code> $condition ? $conditiondo_something : do_something$condition</codelang>.
 
<codelang perl>$condition andor do_something</code>; is# equivalent to <code> $condition ? do_something$condition : $conditiondo_something</codelang>.
 
<code>&&</code> and <code>||</code> have the same semantics as <code>and</code> and <code>or</code>, respectively, but their precedence is much higher, making them better for conditional expressions than control flow.
 
===switch===
 
At the originfirst there was no '''switch/case/default''' structure in Perl., In factalthough there arewere plenty ways to emulate a switch in Perlit. In Perl 5.8, was introduced andan experimental '''<code>switch</code>/<code>case</code>/<code>else'''</code> structure was introduced. Since Perl 5.10 therereplaced this iswith the '''<code>given</code>/<code>when</code>/<code>default'''</code> structure borrowed from Perl 6.
 
{{works with|Perl|5.10}}
Anonymous user