DarkLord1 has asked for the wisdom of the Perl Monks concerning the following question:

I have been working my way through several sections of Peter Wainwright's "Pro Perl." I was, in particular, interested in his approach to redirecting Perl's STDOUT and STDERR filehandles. I entered his code (see below) and got an odd result that I don't understand and, after researching it, can't find any indication of what is going on.

Here is the code snippet:

open(OLDOUT, "> &STDOUT"); my $logfile = 'MyLearn01_log.txt'; open(STDOUT, "> $logfile"); select STDOUT; <...do whatever printing to the new STDOUT...> close(STDOUT); open(STDOUT, "> &OLDOUT);

When I run this snippet I found that a file &STDOUT had been created, as well as the $logfile, MyLearn01_log.txt.

I understand, of course, why the logfile was created. But I don't understand why the file, &STDOUT, was created.

The book doesn't say anything about it (in fact my read is that no such thing should have happened).

I am running version 5.8.8.819 of ActiveState's Perl (I haven't upgraded to 5.10 yet since my IDE doesn't yet support it) under Windows XP.

Does anyone know why &SDTOUT is created?

DarkLord1 Looking for Redemption in the Monastery

Replies are listed 'Best First'.
Re: "Pro Perl's" Redirecting Filehandles - Unexpected Result (space)
by tye (Sage) on Jan 16, 2008 at 04:37 UTC

    Remove the space from "> &". ">&" is an "open mode" like ">>" and "+<" and even ">&=". In modern Perl, you might even prefer to put the mode in a separate argument:

    open( OLDOU­T, ">&", STDOUT ) or die "Can't dup STDOUT to OLDOUT: $!\n";

    - tye        

      Thanks, I'll give it a try.

      I was looking carefully at the material in the book and the author definitely uses the space between the direction mode symbol (the angle bracket) and the special symbol (the ampersand).

      In the previous section (which discusses duplicating files) of the book, the author has a special not that says: "These special modes only work with the two-argument form of open; they do not work with teh mode separated from the name." So I had presumed that the 3-argument form of open wouldn't work. I'll give it a try...maybe the author is wrong.

      Just out of curiosity, in the 2-argument form of open, why in your opinion does the space between the mode specifier (i.e., the angle bracket) and the ampersand cause the problem of creating the mysterious file &STDOUT?

      ack Albuquerque, NM

        Because otherwise how would you open a file named "&STDOUT" if that was what you wanted to do? Before there was 3-argument open, the safe way to open a file was open HANDLE, "> $name" (with the space being important there) and that should be safe even if the user entered "&STDOUT" for $name.

        - tye