#!/usr/bin/perl
use strict;
use warnings;

my $binary  = 'lsof';
my @options = ();

open my $pipe, '-|', $binary, @options
	or die "Error spawning $binary: $!\n";

my ( %name_for, %fds_for );

<$pipe>; # discard column names

while ( <$pipe> ) {
	chomp;
	my ( $cmd, $pid, $fd, $type ) = ( split )[ 0, 1, 3, 4 ];
	$name_for{ $pid } = $cmd;
	$fds_for{ $pid }++;
	#	if $fd =~ /\d/ and $type eq "REG";
}

print "PID\tNAME\t\tOPENFILES\n";

for my $pid ( sort { $fds_for{ $b } <=> $fds_for{ $a } } keys %fds_for ) {
	printf "%d\t%-15s\t%d\n", $pid, $name_for{ $pid }, $fds_for{ $pid };
}
