Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

With[..] not working with $Output

2 views
Skip to first unread message

dh

unread,
Jan 8, 2010, 4:16:52 AM1/8/10
to

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

Leonid Shifrin

unread,
Jan 8, 2010, 6:29:15 AM1/8/10
to
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

Albert Retey

unread,
Jan 8, 2010, 6:38:45 AM1/8/10
to
Hi,

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

0 new messages