paxdiablo paxdiablo - 1 year ago 104
Perl Question

What does "select((select(s),$|=1)[0])" do in Perl?

I've seen some horrific code written in Perl, but I can't make head nor tail of this one:


It's in some networking code that we use to communicate with a server and I assume it's something to do with buffering (since it sets

But I can't figure out why there's multiple
calls or the array reference. Can anyone help me out?

Dan Dan
Answer Source

It's a nasty little idiom for setting autoflush on a filehandle other than STDOUT.

select() takes the supplied filehandle and (basically) replaces STDOUT with it, and it returns the old filehandle when it's done.

So (select($s),$|=1) redirects the filehandle (remember select returns the old one), and sets autoflush ($| = 1). It does this in a list ((...)[0]) and returns the first value (which is the result of the select call - the original STDOUT), and then passes that back into another select to reinstate the original STDOUT filehandle. Phew.

But now you understand it (well, maybe ;)), do this instead:

use IO::Handle;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download