Programming Perl

Programming PerlSearch this book
Previous: 3.2.133 seekdirChapter 3
Functions
Next: 3.2.135 select (ready file descriptors)
 

3.2.134 select (output filehandle)

select FILEHANDLE
select

For historical reasons, there are two select operators that are totally unrelated to each other. See the next section for the other one. This select operator returns the currently selected output filehandle, and if FILEHANDLE is supplied, sets the current default filehandle for output. This has two effects: first, a write or a print without a filehandle will default to this FILEHANDLE. Second, special variables related to output will refer to this output filehandle. For example, if you have to set the same top-of-form format for more than one output filehandle, you might do the following:

select REPORT1;
$^ = 'MyTop';
select REPORT2;
$^ = 'MyTop';

But note that this leaves REPORT2 as the currently selected filehandle. This could be construed as antisocial, since it could really foul up some other routine's print or write statements. Properly written library routines leave the currently selected filehandle the same on exit as it was upon entry. To support this, FILEHANDLE may be an expression whose value gives the name of the actual filehandle. Thus, you can save and restore the currently selected filehandle:

my $oldfh = select STDERR; $| = 1; select $oldfh;

or (being bizarre and obscure):

select((select(STDERR), $| = 1)[0])

This example works by building a list consisting of the returned value from select(STDERR) (which selects STDERR as a side effect) and $| = 1 (which is always 1), but sets autoflushing on the now-selected STDERR as a side effect. The first element of that list (the previously selected filehandle) is now used as an argument to the outer select. Bizarre, right? That's what you get for knowing just enough Lisp to be dangerous.

However, now that we've explained all that, we should point out that you rarely need to use this form of select nowadays, because most of the special variables you would want to set have object-oriented wrapper methods to do it for you. So instead of setting $| directly, you might say:

use FileHandle;
STDOUT->autoflush(1);

And the earlier format example might be coded as:

use FileHandle;
REPORT1->format_top_name("MyTop");
REPORT2->format_top_name("MyTop");


Previous: 3.2.133 seekdirProgramming PerlNext: 3.2.135 select (ready file descriptors)
3.2.133 seekdirBook Index3.2.135 select (ready file descriptors)