Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Dc (computer program)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===Summing all dc expressions as lines from file=== A bare number is a valid dc expression, so this can be used to sum a file where each line contains a single number. This is again implemented with a macro stored in register <code>a</code> which conditionally calls itself, performing an addition each time, until only one value remains on the stack. <syntaxhighlight lang="bash"> dc -e "0d[?+z1<a]dsaxp" < file </syntaxhighlight> The <code>?</code> operator reads another command from the input stream. If the input line contains a decimal number, that value is added to the stack. When the input file reaches end of file, the command is null, and no value is added to the stack. <syntaxhighlight lang="bash"> { echo "5"; echo "7"; } | dc -e "0d[?+z1<a]dsaxp" </syntaxhighlight> And the result is 12. The input lines can also be complex dc commands. <syntaxhighlight lang="bash"> { echo "3 5 *"; echo "4 3 *"; echo "5dd++"; } | dc -e "0d[?+z1<a]dsaxp" </syntaxhighlight> And the result is 42. Note that since dc supports arbitrary precision, there is no concern about numeric overflow or loss of precision, no matter how many lines the input stream contains, unlike a similarly concise solution in [[AWK]]. Downsides of this solution are: the loop stops on encountering a blank line in the input stream (technically, any input line which does not add at least one numeric value to the stack); and, for handling negative numbers, leading instances of '-' to denote a negative sign must be change to '_' in the input stream, because of dc's nonstandard negative sign. The <code>?</code> operator in dc does not provide a clean way to discern reading a blank line from reading end of file.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)