How do I close a file descriptor by number?

This should rarely be necessary, as the Perl close() function is to be used for things that Perl opened itself, even if it was a dup of a numeric descriptor as with MHCONTEXT above. But if you really have to, you may be able to do this:

    require 'sys/syscall.ph';
    $rc = syscall(&SYS_close, $fd + 0);  # must force numeric
    die "can't sysclose $fd: $!" unless $rc == -1;
Or, just use the fdopen(3S) feature of open():

    { 
	local *F; 
	open F, "<&=$fd" or die "Cannot reopen fd=$fd: $!";
	close F;
    }

Back to perlfaq5