What Perl modules are installed for a given Perl installation? Here’s a neat one-liner from Stack Overflow.

/usr/local/bin/perl -MFile::Find=find -MFile::Spec::Functions -Tlwe \
  'find { wanted => sub { print canonpath $_ if /\.pm\z/ }, no_chdir => 1 }, @INC'

Let’s break it down.

/usr/local/bin/perl

This is the path to the Perl binary. On my machine, it’s installed under the /usr/local/bin directory. If you want to use the Perl installation on your $PATH, simply call perl.

-MFile::Find=find -MFile::Spec::Functions

These will execute use 'MODULE' qw('sub'); before executing any code. In this case, we want the find subroutine in File::Find and all of File::Spec::Functions.

-Tlwe

The first switch (-T) enables taint mode. Essentially, Perl will execute certain security checks as it’s running.

The second switch (-l) enables automatic line-ending processing, essentially adding a new line to each print statement.

The third switch (-w) enables warnings (as should always be done in Perl scripts).

The final switch (-e) enables executing the argument passed in on the command line.

find { wanted => sub { print canonpath $_ if /\.pm\z/ }, no_chdir => 1 }, @INC

Let’s add some line breaks and some additional syntactic sugar.

find (
  {
    wanted => sub {
      print canonpath $_ if /\.pm\z/
    },
    no_chdir => 1
  },
  @INC
);

The find subroutine was imported by the -MFile::Find=find option, while wanted and no_chdir are items in the %options input argument to find.

The wanted hash option points to a code reference that performs some task on each file and directory. In this case, each item in @INC has it’s canonpath printed if the item ends with .pm. This filters out directories, and files that are not Perl modules.

The no_chdir hash option to find ensures that chdir() will not be called for each directory as find recurses through the tree.

Of course, TMTOWTDI in Perl. Everyone has their own script or one-liner to list their installed Perl modules.

Is this version better? Probably not, but it works for me.