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

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.

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

Check if a REBOL string contains another string

I tried using the find function to check for the occurrence of the string "ll" in the string "hello", but it returns "ll" instead of true or false:
"This prints 'll'"
print find "hello" "ll"
Does REBOL's standard library have any functions to check if a string contains another string?
Try this
>> print found? find "hello" "ll"
true
>> print found? find "hello" "abc"
false
#ShixinZeng is correct that there is a FOUND? in Rebol. However, it is simply defined as:
found?: function [
"Returns TRUE if value is not NONE."
value
] [
not none? :value
]
As it is equivalent to not none?...you could have written:
>> print not none? find "hello" "ll"
true
>> print not none? find "hello" "abc"
false
Or if you want the other bias:
>> print none? find "hello" "ll"
false
>> print none? find "hello" "abc"
true
Intended to help with readability while using FIND. However, I don't like it because it has confusing behavior by working when not used with FIND, e.g.
>> if found? 1 + 2 [print "Well this is odd..."]
Well this is odd...
Since you can just use the result of the FIND in a conditional expression with IF and UNLESS and EITHER, you don't really need it very often...unless you are assigning the result to a variable you really want to be boolean. In which case, I don't mind using NOT NONE? or NONE? as appropriate.
And in my opinion, losing FOUND? from the core would be fine.
as written in prior answers find gives you back already a result you can use in conditional expressions.
>> either find "hello" "ll" [
[ print "hit"
[ ] [
[ print "no hit"
[ ]
hit
or in a more rebolish way
>> print either find "hello" "ll" [ "hit"] [ "no hit"]
hit
But you can also use to-logic on the result giving you true or false
>> print to-logic find "hello" "ll"
true
>> print find "hello" "lzl"
none
>> print to-logic find "hello" "lzl"
false

Problem with context and property

Let's say I want to generate this output:
public String toString() {
return this.getFirstName() + "," + this.getLastName() + "," + this.getAge();
}
from the template below and a custom recursive build-markup function:
template-toString: {this.get<%property%>() <%either not context.build-markup/EOB [{+ "," +}][""]%> }
build-markup/vars template-toString [property] ["FirstName" "LastName" "Age"]
My problem is to avoid the last element to be concatenate with {+ "," +}
My idea was to use a context.build-markup with an EOB property (End Of Block) that would be set to true when last element is processed. Then I could use in template-toString above either not context.build-markup/EOB [{+ "," +}][""] to concatenate or not with {+ "," +} :
context.build-markup: context [
EOB: false
set 'build-markup func [
{Return markup text replacing <%tags%> with their evaluated results.}
content [string! file! url!]
/vars block-fields block-values
/quiet "Do not show errors in the output."
/local out eval value n max i
][
out: make string! 126
either not vars [
content: either string? content [copy content] [read content]
eval: func [val /local tmp] [
either error? set/any 'tmp try [do val] [
if not quiet [
tmp: disarm :tmp
append out reform ["***ERROR" tmp/id "in:" val]
]
] [
if not unset? get/any 'tmp [append out :tmp]
]
]
parse/all content [
any [
end break
| "<%" [copy value to "%>" 2 skip | copy value to end] (eval value)
| copy value [to "<%" | to end] (append out value)
]
]
][
n: length? block-fields
self/EOB: false
actions: copy []
repeat i n [
append actions compose/only [
;set in self 'EOB (i = n)
set in system/words (to-lit-word pick (block-fields) (i)) get pick (block-fields) (i)
]
]
append actions compose/only [
append out build-markup content
]
foreach :block-fields block-values actions
if any [(back tail out) = "^/" (back tail out) = " " (back tail out) = "," (back tail out) = ";" (back tail out) = "/" (back tail out) = "\"] [
remove back tail out
]
]
out
]
]
But my attempt failed (so I commented ;set in self 'EOB (i = n) because it doesn't work). How to correct the code to get what I want ?
I'm quite certain you could be achieving your goal in a cleaner way than this. Regardless, I can tell you why what you're doing isn't working!
Your n is the expression length? block-fields, and your repeat loop goes up to n. But block-fields contains the single parameter [property]! Hence, it loops from 1 to 1.
You presumably wanted to test against something enumerating over block-values (in this example a range from 1 to 3) and then handle it uniquely if the index reached 3. In other words, your set in self 'EOB expression needs to be part of your enumeration over block-values and NOT block-fields.
This would have given you the behavior you wanted:
n: length? block-values
i: 1
foreach :block-fields block-values compose/only [
set in self 'EOB equal? i n
do (actions)
++ i
]
This absolutely won't work:
append actions compose/only [
set in self 'EOB (i = n)
set in system/words (to-lit-word pick (block-fields) (i)) get pick (block-fields) (i)
]
...because you are dealing with a situation where i and n are both 1, for a single iteration of this loop. Which means (i = n) is true. So the meta-code you get for "actions" is this:
[
set in self 'EOB true
set in system/words 'property get pick [property] 1
]
Next you run the code with a superfluous composition (because there are no PAREN!s, you could just omit COMPOSE/ONLY):
append actions compose/only [
append out build-markup content
]
Which adds a line to your actions meta-code, obviously:
[
set in self 'EOB true
set in system/words 'property get pick [property] 1
append out build-markup content
]
As per usual I'll suggest you learn to use PROBE and PRINT to look and check your expectations at each phase. Rebol is good about dumping variables and such...
You seem to making something simple very complicated:
>> a: make object! [
[ b: false
[ set 'c func[i n] [b: i = n]
[ ]
>> a/b
== false
>> c 1 4
== false
>> a/b
== false
>> c 1 1
== true
>> a/b
== true

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.

Rebol: Found a way to auto-generate and execute code dynamically, is there a better way?

I have experimented with this:
>> code-block: copy []
== []
>> append code-block [func[][print "a"] ]
== [func [] [print "a"]]
>> do do code-block
a
>>
Is there a way to avoid to do "do" twice :)
What you have put into code-block is not the function, but the source of the function, hence the need to do it once to make a function, then do it again as a function.
You can see that like this:
length? code-block
== 3
To just put the function in code-block, can do this:
code-block: copy []
append code-block func[][print "a"] ;; no block around the FUNC
Or this:
code-block: copy []
append code-block reduce [func[][print "a"] ] ;; use REDUCE to evaluate the block
Either way, what is in code-block is now just the function:
length? code-block
== 1
type? first code-block
== function!
do code-block ;; what you asked for!
a