Alister West

home is where your code is ...

Perl Find Open Package FileHandles

Sometimes you want to close all of a programs FH's. I asked this question on "stackoverflow": and I gave a simpler code snippet. Putting a better (but longer) version here.

# Find all package file-handles
sub find_package_filehandles {
    no strict 'refs';

    my $package = shift or return;
    my $seen = shift || {};
    return if $seen->{$package}++;

    my @fds;
    # search package vars
    for my $part (sort keys %{$package}) {
        if (my $fileno = fileno($package.$part)) {
            # print $package.$part." => $fileno\n";
            push @fds, $package.$part;
    # recurse breadth-first
    for my $part (grep /::/, sort keys %{$package}) {
        (my $sub_pkg = $package.$part) =~ s/main:://;
        if (my @_fds = find_package_filehandles($sub_pkg, $seen)) {
            push @fds, @_fds;
    return @fds;
By Alister West