How to bind a variable in parse block - rebol

I just want to iterate through a list of file and after parsing its content print the name of the file:
files: [%test1.txt %test2.txt]
rule: [to "test" thru "test" copy x to "." (print x print file)]
foreach file files [
content: read file
parse [any rule]
]
when executing I have
** Script error: file has no value
How can I bind file var name to the context of rule block program ?

It is also possible to do it this way (put in the RULE literally and let FOREACH to bind it at the right time):
files: [%test1.txt %test2.txt]
rule: [to "test" thru "test" copy x to "." (print x print file)]
foreach file files compose/only/deep [
content: read file
parse content [any (rule)]
]

Just need to bind the rule each iteration:
files: [%test1.txt %test2.txt]
rule: [to "test" thru "test" copy x to "." (print x print file)]
foreach file files [
bind rule 'file
content: read file
parse content [any rule]
]

Related

In Rebol, what is the idiomatic way to read a text file line by line?

For the purpose of reading a text file line by line, without loading the entire file into memory, what is the common way to do this in Rebol?
I am doing the following, but I think (correct me if I'm wrong) that it loads the whole file into memory first:
foreach line read/lines %file.txt [ print line ]
At least with Rebol2
read/lines/direct/part %file.txt 1
should come near to what you want
but if you want all lines one line after the other, it should be like
f: open/lines/direct %test.txt
while [l: copy/part f 1] [print l]
In theory you can supersede any function, even natives. I will try to give a new foreach
foreach_: :foreach
foreach: func [
"Evaluates a block for each value(s) in a series or a file for each line."
'word [get-word! word! block!] {Word or block of words to set each time (will be local)}
data [series! file! port!] "The series to traverse"
body [block!] "Block to evaluate each time"
/local port line
] [
either any [port? data file? data] [
attempt [
port: open/direct/lines data
while [line: copy/part port 1] [
set :word line
do :body
line
]
]
attempt [close port]
] [
foreach_ :word :data :body
]
]
Probably the set :word line part and the attempt should be more elaborated in order to avoid name clashes and get meaningful errors.
Yes open is the way to go. However like sqlab touches on the necessary /lines & /direct refinements are not present in Rebol 3 open (yet).
The good news though is that you can still use open to read in large files in Rebol 3 without these refinements...
file: open %movie.mpg
while [not empty? data: read/part file 32000] [
;
; read in 32000 bytes from file at a time
; process data
]
close file
So you just need to wrap this up into a buffer and process a line at a time.
Here's a crude working example I've put together:
file: open/read %file.txt
eol: newline
buffer-size: 1000
buffer: ""
lines: []
while [
;; start buffering
if empty? lines [
;; fill buffer until we have eol or EOF
until [
append buffer to-string data: read/part file buffer-size
any [
empty? data
find buffer eol
]
]
lines: split buffer eol
buffer: take/last lines
]
line: take lines
not all [empty? data empty? buffer]
][
;; line processing goes here!
print line
]
close file

How do I write contents of a variable to a text file in Rebol 2?

Newbie question here...
I'd like to write the output of the "what" function to a text file.
So here is what I have done:
I've created a variable called "text" and assigned the output of "what" to it
text: [what]
Now I want to write the content of the "text" variable to a txt file...
Any help is appreciated. Thanks in advance!
the easiest way to write the output of statements to a file is to use
echo %file.log
what
with echo none you end this
>> help echo
USAGE:
ECHO target
DESCRIPTION:
Copies console output to a file.
ECHO is a function value.
ARGUMENTS:
target -- (Type: file none logic)
(SPECIAL ATTRIBUTES)
catch
Unfortunately there is not really a value returned from the what function:
Try the following in the console:
print ["Value of `what` is: " what]
So write %filename.txt [what] will not work.
Instead, what you could do is to look at the source of what
source what
which returns:
what: func [
"Prints a list of globally-defined functions."
/local vals args here total
][
total: copy []
vals: second system/words
foreach word first system/words [
if any-function? first vals [
args: first first vals
if here: find args /local [args: copy/part args here]
append total reduce [word mold args]
]
vals: next vals
]
foreach [word args] sort/skip total 2 [print [word args]]
exit
]
See that this function only prints (it doesn't return the values it finds) We can modify the script to do what you want:
new-what: func [
"Returns a list of globally-defined functions."
/local vals args here total collected
][
collected: copy []
total: copy []
vals: second system/words
foreach word first system/words [
if any-function? first vals [
args: first first vals
if here: find args /local [args: copy/part args here]
append total reduce [word mold args]
]
vals: next vals
]
foreach [word args] sort/skip total 2 [append collected reduce [word tab args newline]]
write %filename.txt collected
exit
]
This function is a little hackish (filename is set, but it will return what you want). You can extend the function to accept a filename or do whatever you want. The tab and newline are there to make the file output prettier.
Important things to notice from this:
Print returns unset
Use source to find out what functions do
write %filename value will write out a value to a file all at once. If you open a file, you can write more times.
Fairly elementary: use write if you just want to save some text, read to recover it; use save if you want to store some data and use load to recover it.
>> write %file.txt "Some Text"
>> read %file.txt
== "Some Text"
>> text: [what]
>> save/all %file.r text
>> load %file.r
== [what]
You can get more information on each word at the prompt: help save or view online: load, save, read and write.

Use awk to tarball specified files

I have the following output from repo status:
project X/Y (*** NO BRANCH ***)
-- A/B/c
-m D/E/f
project Z/ (*** NO BRANCH ***)
-- G/H/i
-m J/K/l
(lowercase letters are files, and uppercase are dirs)
The lines prefixed with -- indicate newly added files. repo diff does not include these files, so I can't create a patch that includes all differences. So, I'll just create tarball of them.
Q: What script (e.g., awk, perl, or python) can I use to create a tarball of these files? The tarball should contain:
X/Y/A/B/c
Z/G/H/i
I'm thinking an awk script would be something like this (I'm not that familiar w/syntax):
awk {
BEGIN curdir = '', filelist = []
{
if ($0 == "project") {
curdir = $1
} else if ($0 == "--") {
# insert file specified by $1 into tarball
}
}
}
Ideas? Thanks!
You are close. Here is some suggestion:
/^project/ {
dir = $2
}
$1 == "--" {
fullpath = dir $2 # space between dir and $2 means concatenation
print fullpath
# Do something with fullpath such as
# system("tar ...")
}
Discussion
$1 is the first field (token) in a line, $2 is the second field, and so on
$0 represent the whole record (line)
Every time we see a line that starts with project, we save the directory, $2 to the variable dir
Every time we see the first field of "--", we print out the directory, concatenated with the file name. In your case, insert command to archive the file here.

File reading, writing and appending in TCL

In TCL, how to append different content into a single file using the for loop or foreach loop?
Did you mean something like that?
set fo [open file a]
foreach different_content {"text 1" "text two" "something else" "some content"} {
puts $fo $different_content
}
close $fo
You open file file in mode a (append) and write to the file descriptor ($fo in the example).
Update: If you want to append variable contents, you have to change the script to:
set fo [open file a]
foreach different_content [list $data1 $data2 $data3 $data4] {
puts $fo $different_content
}
close $fo
The following code creates a text file in folder 'P' and writes into it.
set fid [open p:\\temp.txt w]
puts $fid "here is the first line."
close $fid
The following code is fine for reading from a file, where sample.tcl file is available in 'p' folder.
Heading
set fp [open "p://sample.tcl" r]
set file_data [read $fp]
puts $file_data
close $fp

Is it possible to override rebol path operator?

It is possible to overide rebol system words like print, make etc., so is it possible to do the same with the path operator ? Then what's the syntax ?
Another possible approach is to use REBOL meta-programming capabilities and preprocess your own code to catch path accesses and add your handler code. Here's an example :
apply-my-rule: func [spec [block!] /local value][
print [
"-- path access --" newline
"object:" mold spec/1 newline
"member:" mold spec/2 newline
"value:" mold set/any 'value get in get spec/1 spec/2 newline
"--"
]
:value
]
my-do: func [code [block!] /local rule pos][
parse code rule: [
any [
pos: path! (
pos: either object? get pos/1/1 [
change/part pos reduce ['apply-my-rule to-block pos/1] 1
][
next pos
]
) :pos
| into rule ;-- dive into nested blocks
| skip ;-- skip every other values
]
]
do code
]
;-- example usage --
obj: make object! [
a: 5
]
my-do [
print mold obj/a
]
This will give you :
-- path access --
object: obj
member: a
value: 5
--
5
Another (slower but more flexible) approach could also be to pass your code in string mode to the preprocessor allowing freeing yourself from any REBOL specific syntax rule like in :
my-alternative-do {
print mold obj..a
}
The preprocessor code would then spot all .. places and change the code to properly insert calls to 'apply-my-rule, and would in the end, run the code with :
do load code
There's no real limits on how far you can process and change your whole code at runtime (the so-called "block mode" of the first example being the most efficient way).
You mean replace (say)....
print mold system/options
with (say)....
print mold system..options
....where I've replaced REBOL's forward slash with dot dot syntax?
Short answer: no. Some things are hardwired into the parser.