Re: ReadList[file,HeldExpression] ?
- To: mathgroup at smc.vnet.net
- Subject: [mg67637] Re: ReadList[file,HeldExpression] ?
- From: "Norbert Marxer" <marxer at mec.li>
- Date: Mon, 3 Jul 2006 06:37:41 -0400 (EDT)
- References: <e85ful$kf8$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Hi Mark
The following command:
ReadCommandsInFile[fileName_String] :=
Module[{inp, func1, func2}, func1[s_String] := \
StringReplace[StringSplit[s, "="], ";" -> ""];
func2[{s1_String, s2_String}] := StringJoin["Hold[
Set[", s1, ",", s2, "]]"];
inp = StringSplit[Import[fileName, "Text"], "\n"];
Map[FullForm@ToExpression@func2[func1[#]] &, inp]];
ReadCommandsInFile["go.m"]
gives what you want, namely: {Hold[Set[a, 3]], Hold[Set[b, c]]}
Some explanations:
For inp: Import reads the file content as one single string: i.e. in
InputForm "a=3;\nb = c;"
For inp: StringSplit splits this string into a list of strings. The
split is done at each newline (\n). The following list results:
{"a=3;", "b = c;"}
func1 splits these list elements (e.g. "a=c;") at the Set sign "=" and
eliminates the semicolon. The following sublist results: {"a", "3"}
func2 constructs from this (i.e. {"a", "3"} ) the following string:
"Hold[Set[a,3]]"
FullForm and ToExpression finally convert the string to a Mathematica
expression: Hold[Set[a,3]].
Note: If FullForm is not used (or InputForm is used instead), the Set
is replaced by the Set sign =.
With Map you apply the command FullForm@ToExpression@func2[func1[#]] to
each list element (i.e. each line of input).
Best Regards
Norbert Marxer
www.mec.li