Hello,
does anybody have an idea why redirecting output using a With does not
work (version 7 Vista)?
Consider redefining the list $Output:
fun1 := (
old = $Output;
$Output = {OpenWrite["c:/tmp.txt"]};
Print["gaga"];
Close["c:/tmp.txt"];
$Output = old;)
fun1;
fun2 := With[{$Output = {OpenWrite["c:/tmp.txt"]}},
Print["123"];
Close["c:/tmp.txt"];
];
fun2;
Both functions f1 and f2 redefine $Output. fun1 works as expected, it
puts the output from Print in a file. fun2 on the contrary puts nothing
in the file, but writes the output to the screen. Therefore, "With"does
not work in this case.
Daniel
<With> is not supposed to work this way. It is a *lexical* scoping
construct, which means that it binds its variables lexically, i.e. replaces
all explicit occurrences of a variable in its body by a bound value. In this
respect, it is similar to Module (therefore Module won't do what you want
either), the main difference being that With's "variables" are not really
variables, particularly they can not be assigned any value in the body,
because they disappear before the body starts getting evaluated, having been
replaced in the body by their values right before that.
What you are trying to do however is to temporarily redefine a global
variable $Output. For this, you need dynamic scoping, not lexical. For the
effect you seek, use Block instead, and it works.
Regards,
Leonid
Actually f2 also works as expected, at least if you know what With is
doing. You want Block not With, With is just doing the wrong thing for
what you want, and also Module will not work. It is a good example for
the difference of the three...
hth,
albert