Weird Usage Of “select” in perl
Tuesday, December 29th, 2009Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email
Many times while going through some perl code, you must have come across snippets like “select((select(fh), $|=1)[0])” and wondered what this means, even though you might know that:
- $|=1 is used for setting autoflush (i.e. unbuffered data output) and that
- select is used to set the default output to a given file handle instead of STDOUT
Whenever I face any issue with a code fragment, I try to break it down into simpler terms to understand it from the beginning (like I did for my random number generation post). So, these are the steps in which I progressed:
- select(fh) replaces the STDOUT with fh and returns the old filehandle (i.e. STDOUT).
- (select(fh),$|=1) does the above and then sets this new output to autoflush
- From perl’s online docs, I found that the output of the above is a list, the first element of which is the old Filehandle
- So, (select(fh),$|=1)[0] gives us STDOUT
- Then select(select(fh, $|=1)[0]) basically just sets the default output back to STDOUT
So, what is the use of all this. Basically, this is nothing but a trick to set autoflush for any filehandle. Now, there is a very simple way to do this. You just need to include the IO::Handle module (by writing “use IO::Handle;” in your script) and then call “fh->autoflush(1)” on your file handle (Use 0 as parameter to disable autoflushing). This is much cleaner although it means longer run times as your script now has to include and compile lot of new lines of code because the module you added.
© Safer Code | Weird Usage Of “select” in perl
|
Liked this post? Get FREE Updates Subscribe to RSS feed |