At 21:52  -0400 2007/05/19, Terrence Brannon wrote:
I want to write a simple program which:
   * read integers from stdin, one line at a time
   * print the sum of those integers

------
Terrence,

More than you asked for ... I like using #! scripts in Linux
and Darwin. I keep a template for writing such scripts -

#! /usr/local/bin/ja
   localverbs =: 3 : 'may be defined here'
3 : 0 ARGV
 try. NB. catch errors.
  'call parms stin' =: getargs 'no fancy parms...'
    NB. parms e.g. -a10 <-> (,'a');'10'
   if. ((0 = #stin) *. 3 > # call) do.
    stderr 'Usage: ',(;1{call), ' argument list',NL
    exit 2
   else.
     NB. Do the work here
     stdout 'some result'
   end.
 catch.
  stderr 13!:12 ''  NB. at the very least...
 end.
exit 0
)

I use a link "ja" to invoke /usr/local/lib/j601/jconsole - I often
discard parts of the template like the error catching stuff. If the
script is ambivalent about stdin or file names, parms etc. then
some extra logic is needed in the stderr section. The verb getargs
is handy in that it separates the "call", "parms", and "stin" --

   getargs =: 3 : 0
  ARGV getargs y
:
NB. need jmf to pickup definition of c_isatty_jmf_
  require 'jmf'
  argb =. (]`(([: < 1: {. }.) , [: < 2: }. ])@.('-'"_ = {.))&.> x
  NB. The above boxes parms (elements starting with "-" returning name;value
  parm =. 32 = ;(3!:0)&.> argb
  ((-. parm)#argb);(>parm#argb);(". ({. 0 = >c_isatty_jmf_ 0)#'stdin ''''')
)

Notice that by explicitly passing ARGV in the #! script, you could
use "y" in the definitions. The definition of "getargs" is in a local
profile that I keep load by default.

Here is a cut at your original request based on the stuff above and
the saved file "sumcol-input.txt" from the web link you gave.

iMg5:~/Desktop jkt$ wc sumcol-input.txt
    1000    1000    4393 sumcol-input.txt
iMg5:~/Desktop jkt$ head sumcol-input.txt
276
498
-981
770
-401
702
966
950
-853
-53
iMg5:~/Desktop jkt$ cat colsum
#! /usr/local/bin/ja
3 : 0 ARGV
'call parms stin' =: getargs 'no fancy parms...' NB. parms e.g. -a10 <-> (,'a');'10'
   if. ((0 = #stin) *. 3 > # call) do.
    stderr 'Usage: ',(;1{call), ' "file_name" OR cat file | ', (;1{call), NL
exit 2
   else.
    if. (0 = #stin) do. stin =: 1!:1 ] 2{call end.
     stdout NL,~ ": +/ 0&". ;._2 > stin
   end.
exit 0
)

iMg5:~/Desktop jkt$ ./colsum
Usage: ./colsum "file_name" OR cat file | ./colsum
iMg5:~/Desktop jkt$ ./colsum sumcol-input.txt
500
iMg5:~/Desktop jkt$ cat sumcol-input.txt | ./colsum
500
iMg5:~/Desktop jkt$

If you have questions/suggestions - let me know.

- joey


----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to