Comma quibbling: Difference between revisions
Content deleted Content added
Add ed example |
|||
(4 intermediate revisions by one other user not shown) | |||
Line 1,613:
("ABC" "DEF" "G" "H") ----> "{ ABC, DEF, G and H }"
</syntaxhighlight>
=={{header|ed}}==
Uses basic regular expressions (BREs).
<syntaxhighlight lang="sed">
# by Artyom Bologov
H
,p
g/.*/s/ /, /g
g/[,]/s/,\([^,]*\)$/ and\1/
g/.*/s//{&}/
,p
Q
</syntaxhighlight>
{{out}}
<pre>$ ed -s comma-quibling.input < comma-quibling.ed
Newline appended
ABC
ABC DEF
ABC DEF G H
{}
{ABC}
{ABC and DEF}
{ABC, DEF, G and H}</pre>
=={{header|Eiffel}}==
Line 3,425 ⟶ 3,453:
<syntaxhighlight lang="php"><?php
function quibble($arr) {
case 0:
return '{}';
case 1:
return "{{$arr[0]}}";
default:
$right = array_slice($arr, -1)[0];
return "{{$left} and {$right}}";
}
}
Line 3,451 ⟶ 3,482:
foreach ($tests as $test) {
echo quibble($test) . PHP_EOL;
}
?></syntaxhighlight>
{{out}}
<pre>{}
Line 4,547 ⟶ 4,579:
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
{{works with|Korn Shell}}
{{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}}
<syntaxhighlight lang="zsh">quibble() {
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
|