Comma quibbling: Difference between revisions
m
→{{header|PHP}}: fix formatting.
m (→{{header|dc}}: Better register names and comments.) |
m (→{{header|PHP}}: fix formatting.) |
||
(4 intermediate revisions by the same user not shown) | |||
Line 1,475:
[(p)rint: get next item from stack in r register and print it. If there are
more than 2 items left
print " and " (a) and return.]sx
[ Lr n 2 yr >c 2 yr =a 2 yr >p]sp
Line 3,424 ⟶ 3,425:
<syntaxhighlight lang="php"><?php
function quibble($arr) {
case 0:
return '{}';
case 1:
return
return '{'.$arr[0].' and '.$arr[1].'}';▼
default:
$right = array_slice($arr, -1)[0];
}▼
▲ }
}
Line 3,450 ⟶ 3,454:
foreach ($tests as $test) {
echo quibble($test) . PHP_EOL;
}▼
}</syntaxhighlight>▼
?></syntaxhighlight>
{{out}}
<pre>{}
Line 4,546 ⟶ 4,551:
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
{{works with|Korn Shell}}
<syntaxhighlight lang="bash">quibble() {▼
{{works with|Z Shell}}
<syntaxhighlight lang="bash">
quibble() {
printf '{'
shift
done
if (( $# )); then
▲}
printf '%s' "$1"
shift
fi
if (( $# )); then
printf ' and %s' "$1"
fi
printf '%s\n' '}'
▲}</syntaxhighlight>
With a slight modification, it will work in any POSIX shell, or even older Bourne-compatible shells as long as they have functions and <b>printf</b>:
<syntaxhighlight lang="sh">
quibble() {
printf '{'
while [ $# -gt 2 ]; do
printf '%s, ' "$1"
shift
done
if [ $# -gt 0 ]; then
printf '%s' "$1"
shift
fi
if [ $# -gt 0 ]; then
printf ' and %s' "$1"
fi
printf '%s\n' '}'
}</syntaxhighlight>
Going the other way, Zsh-specific code can be more compact:
{{works with|Z Shell}}
printf '{'
if (( $# > 1 )) printf '%s and ' ${(j:, :)@[1,-2]}
printf '%s}\n' $@[-1]
}</syntaxhighlight>
The test code is the same either way:
<syntaxhighlight lang="sh">
quibble
quibble ABC
|