【发布时间】:2010-12-27 13:30:37
【问题描述】:
有没有一种聪明的方法来检测你的系统中是否安装了某个 Perl 模块? 我以前的愚蠢方法是编写一个 Perl 脚本,其中我唯一要做的就是使用该模块。如果运行检测脚本时没有任何声音,那么我知道模块已经安装,尽管我仍然不知道模块安装在哪个版本和位置。
提前致谢。
【问题讨论】:
有没有一种聪明的方法来检测你的系统中是否安装了某个 Perl 模块? 我以前的愚蠢方法是编写一个 Perl 脚本,其中我唯一要做的就是使用该模块。如果运行检测脚本时没有任何声音,那么我知道模块已经安装,尽管我仍然不知道模块安装在哪个版本和位置。
提前致谢。
【问题讨论】:
我所知道的最短的事情不涉及脚本或 shell 别名:
$ perl -MFoo::Bar\ 99
Foo::Bar version 99 required--this is only version 1.234.
(如果未安装,则通常是关于不在@INC 中的消息)
对于好奇的人,这与perl -e 'use Foo::Bar 99' 相同。
【讨论】:
cpan -D Foo::Bar 稍微短一些。 :)
instmodsh
NAME
instmodsh - A shell to examine installed modules
SYNOPSIS
instmodsh
DESCRIPTION
A little interface to ExtUtils::Installed to examine installed modules, validate your packlists and even create a tarball from an installed module.
SEE ALSO
ExtUtils::Installed
【讨论】:
instmodsh 是一个 shell 的事实使得使用起来有点尴尬 - 您需要多个交互步骤才能获得所需的信息,而我可以找到 location i> 的一个模块,似乎没有办法获得 version。另一方面,使用l 命令是查看所有非核心模块(可能随特定发行版提供或用户稍后安装)的便捷方式。
instmodsh 不会找到不是通过*.packlist 文件安装的模块。
这是一个执行此操作的程序:
#!/usr/bin/perl
# testmod - test to see if a module is available
use strict;
use warnings;
my $mod = (shift @ARGV) || die "usage: $0 module\n";
# convert module-name to path
my $file = $mod;
$file =~ s{::}{/}gsmx;
$file .= '.pm';
# Pull in the module, if it exists
eval { require $file }
or die "can't find module $mod\n";
# Get the version from the module, if defined
my $ver;
{ no strict 'refs';
$ver = ${$mod . "::VERSION"} || 'UNKNOWN';
}
# And its location
my $from = $INC{$file};
print "module $mod is version $ver loaded from $from\n";
【讨论】:
我使用这些 bash 函数/Perl oneliners 来查找 Perl 模块的版本号和位置:
# equivalent to perldoc -l <module>
perlwhere() {
perl -wle'eval "require $ARGV[0]" or die; ($mod = $ARGV[0]) =~ s|::|/|g; print $INC{"${mod}.pm"}' $1
}
perlversion() {
perl -M$1 -wle'print $ARGV[0]->VERSION' $1
}
: [ether ~].2$; perlwhere Test::More
/usr/lib/perl5/5.8.8/Test/More.pm
: [ether ~].2$; perlversion Test::More
0.94
【讨论】:
我不知道是否有任何聪明的方法。但是我通常
做的是使用 perldoc 的 '-l' 或 '-m' 选项。例如:
%perldoc -l XML::Simple
输出如下所示,是模块文件的完整路径
.../lib/XML/Simple.pm
与您的方法相比,这种方法的优势在于,如果安装了模块
输出包含模块位置的路径。但是,当模块不是
已安装
或者如果它没有 perldoc,则显示的错误消息是 "No documentation found for ...",
无法区分错误是由于缺少模块还是缺少
文档。在这种情况下,-m 选项会变得很方便,因为它会打印整个
文件的内容以及路径。
【讨论】:
perldoc -ml XML::LibXML::Document 为您提供.pm 文件的路径,即使有单独的.pod 文件。
pmvers 实用程序和其他 pmtools 将满足您的需求。否则,这里是查找模块版本的单线:
perl -le 'eval "require $ARGV[0]" and print $ARGV[0]->VERSION' Some::Module
【讨论】:
perl -le 'eval "require $ARGV[0]" or die; print $ARGV[0]->VERSION' Some::Module
如果您正在寻找跨平台 CLI(Linux、OSX、Windows),请考虑我的 whichpm utility;例如:
# Locate the Data::Dumper module, and also print
# version information and core-module status.
$ whichpm -v Data::Dumper
Data::Dumper 2.145 core>=5.005 /usr/lib/perl/5.18/Data/Dumper.pm
它还可以发现意外重复并列出所有已安装的模块。
如果你碰巧安装了 Node.js / io.js,你可以从 npm 注册表安装它:
[sudo] npm install whichpm -g
有关手动安装说明等更多信息,请参阅the repo;这是latest version 的直接下载链接(将保持最新状态)。
【讨论】: