18

Possible Duplicate:
Ruby $stdout vs. STDOUT

Is STDERR generally preferred over using $stderr, or vice versa?

And what about STDOUT vs $stdout?

Community
  • 1
  • 1
dan
  • 43,914
  • 47
  • 153
  • 254

1 Answers1

22

To the contrary, using $stderr is preferrable.

The reason for that is that $stderr as a global variable can be reassigned, while STDERR as a constant shouldn't be reassigned (it raises a warning).

Usually they both point to the same standard error file, but in some cases you might want to temporarily redirect all your output somewhere else (for example, to a log file or into a string buffer), in which case you can just reassign $stderr and all your code will respect that (if you were smart enough to use $stderr instead of STDERR in the first place).

Niklas B.
  • 92,950
  • 18
  • 194
  • 224
  • Although I don't know whether the internal functions use `STDERR` or `$stderr`. You may have to perform all writes and reads explicitly, at which point you should use a dedicated other variable. – Linuxios Mar 17 '12 at 00:02
  • @Linux: Which "internal functions" would write to stderr? The only thing that comes to my mind are warnings, which you can eradicate by fixing them. – Niklas B. Mar 17 '12 at 00:04
  • Sorry. I meant `STDOUT` and `$stdout` in relation to `puts` and `gets`. Whoops. – Linuxios Mar 17 '12 at 00:06
  • 1
    @Linux: You can always use `$stdout.puts` if you want to be explicit, or even better, write a small abstraction layer on top of it. – Niklas B. Mar 17 '12 at 00:08
  • I know. But if you want to do it explicitly, it will be clearer to use a dedicated variable. Constantly assigning `$stdout` is not very clear, especially if you don;t know much of the variable. – Linuxios Mar 17 '12 at 01:12
  • Changing $stderr to something other than stderr would be inadvisable. If you don't want output to go to stderr, explicitly redirect somewhere else, don't reassign $stderr. That just seems like basic good practice in any language. This way lies Obfuscated Perl. – Keith Tyler Jul 12 '16 at 23:30