Selective file copy: Difference between revisions

J
(Selective file copy in FreeBASIC)
(J)
Line 592:
{"A":"AAAAA","C":"5","X":"XXXXX"}
</pre>
 
=={{header|J}}==
Here's some exposition, roughly imitating the {{#COBOL|COBOL}} implementation.
 
(Remember: J's prompt is three spaces, so indented lines here are J sentences, and the following line(s) is/are the result(s) from the sentence.)
 
First, we'll build the file and write it:<lang J> N=: {{(}.":1e4+y),'+-'{~3<y}}
R=: {{5{.y#x}}
('A'&R,'B'&R,N,'D'&R)&>1+i.5
A B 0001+D
AA BB 0002+DD
AAA BBB 0003+DDD
AAAA BBBB 0004-DDDD
AAAAABBBBB0005-DDDDD
(('A'&R,'B'&R,N,'D'&R)&>1+i.5) fwrite 'example'
100</lang>
 
Note that we've written 100 characters here -- there's no newlines in this file:
 
<lang J> fread'example'
A B 0001+D AA BB 0002+DD AAA BBB 0003+DDD AAAA BBBB 0004-DDDD AAAAABBBBB0005-DDDDD</lang>
 
So we'll need to parse the file based on our knowledge of it -- 20 character lines, and four five character wide fields. In the spirit of the task, we'll code this up as if the fields could be arbitrary (different) widths. But, for conciseness, we'll not show the bit where we would add up the field widths to find the record width:<lang J> (##\)5 5 5 5
1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4
_20 ((##\)5 5 5 5)&(</.)\fread 'example'
┌─────┬─────┬─────┬─────┐
│A │B │0001+│D │
├─────┼─────┼─────┼─────┤
│AA │BB │0002+│DD │
├─────┼─────┼─────┼─────┤
│AAA │BBB │0003+│DDD │
├─────┼─────┼─────┼─────┤
│AAAA │BBBB │0004-│DDDD │
├─────┼─────┼─────┼─────┤
│AAAAA│BBBBB│0005-│DDDDD│
└─────┴─────┴─────┴─────┘</lang>
 
So that's the characters of the records from the file. We can assign these records to variables -- one for each column:<lang J> 'A B C D'=: |:_20 ((##\)5 5 5 5)&(</.)\fread 'example'
A
A
AA
AAA
AAAA
AAAAA</lang>
 
Also, we want numeric values for that third column. Here's building up to that, and giving the numeric column variable a name:<lang J> C
0001+
0002+
0003+
0004-
0005-
_1|."1 C
+0001
+0002
+0003
-0004
-0005
0"._1|."1 C
1 2 3 _4 _5
,.0"._1|."1 C
1
2
3
_4
_5
N=: ,.0"._1|."1 C</lang>
 
Next, we'll want N as a five character wide column -- here, it makes sense to use J's " [https://www.jsoftware.com/help/dictionary/dx008.htm 8!:x format]" mechanism -- and we'll want a fill column: <lang J> '5.0' 8!:2 N
1
2
3
-4
-5
5#'X'
XXXXX</lang>
 
Finally, we'll glue the pieces back together and write that to a file:<lang J> A,"1('5.0' 8!:2,.N),"1(5#'X')
A 1XXXXX
AA 2XXXXX
AAA 3XXXXX
AAAA -4XXXXX
AAAAA -5XXXXX
(A,"1('5.0' 8!:2,.N),"1(5#'X')) fwrite 'output'
75</lang>
 
Again, there's no newlines in the result file, so we would have to know something about its record structure to make sense of it:
 
<lang> fread 'output'
A 1XXXXXAA 2XXXXXAAA 3XXXXXAAAA -4XXXXXAAAAA -5XXXXX
_15 ]\fread 'output'
A 1XXXXX
AA 2XXXXX
AAA 3XXXXX
AAAA -4XXXXX
AAAAA -5XXXXX</lang>
 
 
=={{header|Java}}==
6,951

edits