CPAN(3pm)
π CPAN(3pm) β the manual, but make it group chat π
Manual name: CPAN(3pm), straight from the Perl Programmers Reference Guide. Yes bestie, it's CPAN β the thing that queries, downloads, and builds perl modules from CPAN sites. We're doing this together, no cap.
β¨ NAME β¨
CPAN - query, download and build perl modules from CPAN sites. π
π οΈ SYNOPSIS π οΈ
okay so here's the vibe: interactive mode first, then basic commands. These are literal, so copy them exactly, mwah. π«Ά
Interactive mode:
perl -MCPAN -e shell
--or--
cpan
Basic commands:
# Modules:
cpan> install Acme::Meta # in the shell
CPAN::Shell->install("Acme::Meta"); # in perl
# Distributions:
cpan> install NWCLARK/Acme-Meta-0.02.tar.gz # in the shell
CPAN::Shell->
install("NWCLARK/Acme-Meta-0.02.tar.gz"); # in perl
# module objects:
$mo = CPAN::Shell->expandany($mod);
$mo = CPAN::Shell->expand("Module",$mod); # same thing
# distribution objects:
$do = CPAN::Shell->expand("Module",$mod)->distribution;
$do = CPAN::Shell->expandany($distro); # same thing
$do = CPAN::Shell->expand("Distribution",
$distro); # same thing
πΈ DESCRIPTION πΈ
okay so the CPAN module automates β or at least makes way easier β the make and install of perl modules and extensions. It's got some primitive searching capabilities (iconic), and it knows how to use LWP, HTTP::Tiny, Net::FTP, and certain external download clients to fetch distributions from the net. slay. π
Those distributions get fetched from one or more mirrored CPAN (Comprehensive Perl Archive Network) sites and unpacked in a dedicated directory. Dedicated, bestie. It's giving organized. ποΈ
The CPAN module also supports named and versioned bundles of modules. Bundles simplify handling sets of related modules β see Bundles below. π
The package contains a session manager and a cache manager. The session manager keeps track of what has been fetched, built, and installed in the current session. The cache manager keeps track of the disk space occupied by the make processes and deletes excess space using a simple FIFO mechanism. Literally FIFO, no cap. π¦
All methods provided are accessible in a programmer style and in an interactive shell style. So whether you're coding or vibing in the shell, you're covered. π
π CPAN::shell([$prompt, $command]) Starting Interactive Mode π
Enter interactive mode by running
perl -MCPAN -e shell
or
cpan
which puts you into a readline interface. If Term::ReadKey and either of Term::ReadLine::Perl or Term::ReadLine::Gnu are installed, history and command completion are supported. So cute. β¨
Once at the command line, type h for one-page help screen; the rest should be self-explanatory. fr fr.
The function call shell takes two optional arguments: one the prompt, the second the default initial command line (the latter only works if a real ReadLine interface module is installed).
The most common uses of the interactive modes areβ¦
π Searching for authors, bundles, distribution files and modules π
There are corresponding one-letter commands a, b, d, and m for each of the four categories and another, i, for any of the mentioned four. Each of the four entities is implemented as a class with slightly differing methods for displaying an object. So the one-letter squad is real. iykyk. π
Arguments to these commands are either strings exactly matching the identification string of an object, or regular expressions matched case-insensitively against various attributes of the objects. The parser only recognizes a regular expression when you enclose it with slashes. So m /lorem/? slay. But m lorem without slashes? not a regex to the parser, bestie. π―
The principle is that the number of objects found influences how an item is displayed. If the search finds one item, the result is displayed with the rather verbose method as_string, but if more than one is found, each object is displayed with the terse method as_glimpse. One result = verbose; many results = terse. Periodt. β¨
Examples:
cpan> m Acme::MetaSyntactic
Module id = Acme::MetaSyntactic
CPAN_USERID BOOK (Philippe Bruhat (BooK) <[...]>)
CPAN_VERSION 0.99
CPAN_FILE B/BO/BOOK/Acme-MetaSyntactic-0.99.tar.gz
UPLOAD_DATE 2006-11-06
MANPAGE Acme::MetaSyntactic - Themed metasyntactic variables names
INST_FILE /usr/local/lib/perl/5.10.0/Acme/MetaSyntactic.pm
INST_VERSION 0.99
cpan> a BOOK
Author id = BOOK
EMAIL [...]
FULLNAME Philippe Bruhat (BooK)
cpan> d BOOK/Acme-MetaSyntactic-0.99.tar.gz
Distribution id = B/BO/BOOK/Acme-MetaSyntactic-0.99.tar.gz
CPAN_USERID BOOK (Philippe Bruhat (BooK) <[...]>)
CONTAINSMODS Acme::MetaSyntactic Acme::MetaSyntactic::Alias [...]
UPLOAD_DATE 2006-11-06
cpan> m /lorem/
Module = Acme::MetaSyntactic::loremipsum (BOOK/Acme-MetaSyntactic-0.99.tar.gz)
Module Text::Lorem (ADEOLA/Text-Lorem-0.3.tar.gz)
Module Text::Lorem::More (RKRIMEN/Text-Lorem-More-0.12.tar.gz)
Module Text::Lorem::More::Source (RKRIMEN/Text-Lorem-More-0.12.tar.gz)
cpan> i /berlin/
Distribution BEATNIK/Filter-NumberLines-0.02.tar.gz
Module = DateTime::TimeZone::Europe::Berlin (DROLSKY/DateTime-TimeZone-0.7904.tar.gz)
Module Filter::NumberLines (BEATNIK/Filter-NumberLines-0.02.tar.gz)
Author [...]
The examples illustrate several aspects: the first three queries target modules, authors, or distros directly and yield exactly one result. The last two use regular expressions and yield several results. The last one targets all of bundles, modules, authors, and distros simultaneously. When more than one result is available, they are printed in one-line format. Cute, efficient, iconic. β¨
π¦ get, make, test, install, clean modules or distributions π¦
These commands take any number of arguments and investigate what is necessary to perform the action. Argument processing is as follows:
known module name in format Foo/Bar.pm module
other embedded slash distribution
- with trailing slash dot directory
enclosing slashes regexp
known module name in format Foo::Bar module
If the argument is a distribution file name (recognized by embedded slashes), it is processed. If it is a module, CPAN determines the distribution file in which this module is included and processes that, following any dependencies named in the module's META.yml or Makefile.PL (this behavior is controlled by the configuration parameter prerequisites_policy). If an argument is enclosed in slashes it is treated as a regular expression: it is expanded and if the result is a single object (distribution, bundle or module), this object is processed. So slashes = regex mode, got it. π―
Example:
install Dummy::Perl # installs the module
install AUXXX/Dummy-Perl-3.14.tar.gz # installs that distribution
install /Dummy-Perl-3.14/ # same if the regexp is unambiguous
get downloads a distribution file and untars or unzips it, make builds it, test runs the test suite, and install installs it. The whole pipeline, bestie. π₯
Any make or test is run unconditionally. An install <distribution_file> is also run unconditionally. But for install <module>, CPAN checks whether an install is needed and prints module up to date if the distribution file containing the module doesn't need updating. So it's not out here reinstalling for no reason. π
CPAN also keeps track of what it has done within the current session and doesn't try to build a package a second time regardless of whether it succeeded or not. It does not repeat a test run if the test has been run successfully before. Same for install runs. Memory? iconic. π§
The force pragma may precede another command (currently: get, make, test, or install) to execute the command from scratch and attempt to continue past certain errors. See the section below on the force and the fforce pragma. πͺ
The notest pragma skips the test part in the build process. Sometimes you just need to skip the vibe check. π
Example:
cpan> notest install Tk
A clean command results in a make clean being executed within the distribution file's working directory. Tidy. π§Ή
π readme, perldoc, look module or distribution π
readme displays the README file of the associated distribution. Look gets and untars (if not yet done) the distribution file, changes to the appropriate directory and opens a subshell process in that directory. perldoc displays the module's pod documentation in html or plain text format. Three little helpers, all iconic. π«Ά
ποΈ ls author / ls globbing_expression ποΈ
The first form lists all distribution files in and below an author's CPAN directory as stored in the CHECKSUMS files distributed on CPAN. The listing recurses into subdirectories. So yes, it goes deep. π³οΈ
The second form limits or expands the output with shell globbing as in the following examples:
ls JV/make*
ls GSAR/*make*
ls */*make*
The last example is very slow and outputs extra progress indicators that break the alignment of the result. Not the vibe, but okay. π
Note: globbing only lists directories explicitly asked for, for exampleFOO/*will not listFOO/bar/Acme-Sthg-n.nn.tar.gz. This may be regarded as a bug that may be changed in some future version. Bestie, it's a little quirk. π
π failed π
The failed command reports all distributions that failed on one of make, test or install for some reason in the currently running shell session. So you can see what flopped this session. No judgment. π
πΎ Persistence between sessions πΎ
If the YAML or the YAML::Syck module is installed a record of the internal state of all modules is written to disk after each step. The files contain a signature of the currently running perl version for later perusal. So your state is saved, bestie. π
If the configurations variable build_dir_reuse is set to a true value, then CPAN.pm reads the collected YAML files. If the stored signature matches the currently running perl, the stored state is loaded into memory such that persistence between sessions is effectively established. It's giving continuity. β¨
π The force and the fforce pragma π
To speed things up in complex installation scenarios, CPAN.pm keeps track of what it has already done and refuses to do some things a second time. A get, a make, and an install are not repeated. A test is repeated only if the previous test was unsuccessful. The diagnostic message when CPAN.pm refuses to do something a second time is one of Has already been "unwrapped|made|tested successfully" or something similar. Another situation where CPAN refuses to act is an install if the corresponding test was not successful. So it's not being stubborn for no reason. π
In all these cases, the user can override this stubborn behaviour by prepending the command with the word force, for example:
cpan> force get Foo
cpan> force make AUTHOR/Bar-3.14.tar.gz
cpan> force test Baz
cpan> force install Acme::Meta
Each forced command is executed with the corresponding part of its memory erased. Dramatic? Maybe. But that's the deal. πβ¨
LOCKFILE π
okay so interactive sessions keep a lockfile β by default it lives at ~/.cpan/.lock. bestie, batch jobs are the chill ones: they can totally run without a lockfile and they won't disturb each other, no drama. π
but here's the tea: when another process is already holding the lockfile, the shell will offer to run in downgraded mode. that's an experimental feature and ngl it's not tested very well yet π. that second shell doesn't write the history file, doesn't use the metadata file, and gets a different prompt. so like, it's cosplaying as a shell but it's lowkey a limited edition version. β¨
SIGNALS π‘
CPAN.pm installs signal handlers for SIGINT and SIGTERM. while you're in the cpan-shell, the whole intention is that you can press ^C anytime and just... return to the cpan-shell prompt. very demure, very mindful. π
a SIGTERM will cause the cpan-shell to clean up and leave the shell loop. and if you want to emulate the effect of a SIGTERM? send two consecutive SIGINTs β which usually just means pressing ^C twice. iconic little trick tbh. π
CPAN.pm ignores SIGPIPE. if the user sets inactivity_timeout, a SIGALRM gets used during the run of the perl Makefile.PL or perl Build.PL subprocess. a SIGALRM is also used during module version parsing, and that one is controlled by version_timeout. β°
π» CPAN::Shell
so the commands available in the shell interface? they're literally methods in the package CPAN::Shell. when you enter a shell command, your input gets split by the Text::ParseWords::shellwords() routine, which acts like most shells do. π
- the first word is interpreted as the method to be invoked
- the rest of the words are treated as the method's arguments
and yes, continuation lines are supported β you just end a line with a literal backslash \. so you can be dramatic and write a whole saga across lines. β¨
π¦ autobundle
autobundle writes a bundle file into the $CPAN::Config->{cpan_home}/Bundle directory. the file contains a list of all modules that are both available from CPAN and currently installed within @INC. duplicates of each distribution are suppressed β we don't do repeats here. π
the name of the bundle file is based on the current date and a counter, e.g. Bundle/Snapshot_2012_05_21_00.pm. you install it again by running cpan Bundle::Snapshot_2012_05_21_00, or by installing Bundle::Snapshot_2012_05_21_00 from the CPAN shell. ποΈ
return value: the path to the written file. slay, it tells you where it put it. π«Ά
π hosts
note: this feature is still in alpha state and may change in future versions of CPAN.pm. so like, don't get too attached bestie. π
this command provides a statistical overview over recent download activities. the data for this is collected in the YAML file FTPstats.yml in your cpan_home directory. π
but lowkey, if no YAML module is configured or YAML isn't installed, or if ftpstats_size is set to a value <=0, then no stats are provided. nothing. zero. the void. π
β install_tested
installs all distributions that have been tested successfully but have not yet been installed. see also is_tested. it's giving "finish what you started" energy fr fr. π₯
π is_tested
lists all build directories of distributions that have been tested successfully but have not yet been installed. see also install_tested. the chaotic sibling of the command above. π«Ά
π οΈ mkmyconfig
mkmyconfig() writes your own CPAN::MyConfig file into your ~/.cpan/ directory so that you can save your own preferences instead of the system-wide ones. main character energy: your config, your rules. π
π r [Module|/Regexp/]...
scans the current perl installation for modules that have a newer version available on CPAN and provides a list of them. β¨
- called without an argument β all potential upgrades are listed
- called with arguments β the list is filtered to the modules and regexps you gave as arguments
the listing looks something like this:
Package namespace installed latest in CPAN file
CPAN 1.94_64 1.9600 ANDK/CPAN-1.9600.tar.gz
CPAN::Reporter 1.1801 1.1902 DAGOLDEN/CPAN-Reporter-1.1902.tar.gz
YAML 0.70 0.73 INGY/YAML-0.73.tar.gz
YAML::Syck 1.14 1.17 AVAR/YAML-Syck-1.17.tar.gz
YAML::Tiny 1.44 1.50 ADAMK/YAML-Tiny-1.50.tar.gz
CGI 3.43 3.55 MARKSTOS/CGI.pm-3.55.tar.gz
Module::Build::YAML 1.40 1.41 DAGOLDEN/Module-Build-0.3800.tar.gz
TAP::Parser::Result::YAML 3.22 3.23 ANDYA/Test-Harness-3.23.tar.gz
YAML::XS 0.34 0.35 INGY/YAML-LibYAML-0.35.tar.gz
it suppresses duplicates in the column "in CPAN file" such that distributions with many upgradeable modules are listed only once. no spam in the chat. π
note that the list is not sorted. that's just how it is, bestie. don't come for me. π
π recent EXPERIMENTAL COMMAND
the recent command downloads a list of recent uploads to CPAN and displays them slowly. while the command is running, a $SIG{INT} exits the loop after displaying the current item. π
note: this command requires XML::LibXML installed.
note: this whole command currently is just a hack and will probably change in future versions of CPAN.pm, but the general approach will likely remain.
note: see also smoke. π
π recompile
recompile() is a special command that takes no argument and runs the make/test/install cycle with brute force over all installed dynamically loadable extensions (a.k.a. XS modules) with 'force' in effect. πͺ
the primary purpose of this command is to finish a network installation. imagine this scenario:
- you have a common source tree for two different architectures
- you decide to do a completely independent fresh installation
- you start on one architecture with the help of a Bundle file produced earlier
- CPAN installs the whole Bundle for you
- but when you try to repeat the job on the second architecture, CPAN responds with a
"Foo up to date"message for all modules π
so you invoke CPAN's recompile on the second architecture and you're done. periodt. π
another popular use for recompile is to act as a rescue in case your perl breaks binary compatibility. if one of the modules that CPAN uses is in turn depending on binary compatibility (so you literally cannot run CPAN commands), then you should try the CPAN::Nox module for recovery. π«Ά
π report Bundle|Distribution|Module
the report command temporarily turns on the test_report config variable, then runs the force test command with the given arguments. the force pragma reruns the tests and repeats every step that might have failed before. it's giving "we're running it back" energy. π₯
π¨ smoke EXPERIMENTAL COMMAND
* WARNING: this command downloads and executes software from CPAN to your computer of completely unknown status. You should never do this with your normal account and better have a dedicated well separated and secured machine to do this. *
like bestie I cannot stress this enough β this is the "do NOT try this at home" of CPAN commands. π
the smoke command takes the list of recent uploads to CPAN as provided by the recent command and tests them all. while the command is running $SIG{INT} is defined to mean that the current item shall be skipped. βοΈ
note: this whole command currently is just a hack and will probably change in future versions of CPAN.pm, but the general approach will likely remain.
note: see also recent.
β¬οΈ upgrade [Module|/Regexp/]...
the upgrade command first runs an r command with the given arguments and then installs the newest versions of all modules that were listed by that. so it's basically r + install but make it a single serve. π
π The four "CPAN::*" Classes: Author, Bundle, Module, Distribution
although it may be considered internal, the class hierarchy does matter for both users and programmer. CPAN.pm deals with the four classes mentioned above, and those classes all share a set of methods. classical single polymorphism is in effect. a metaclass object registers all objects of all kinds and indexes them with a string. β¨
the strings referencing objects have a separated namespace (well, not completely separated):
- words containing a
/(slash) β Distribution - words starting with
Bundle::β Bundle - everything else β Module or Author
Modules know their associated Distribution objects. they always refer to the most recent official release. developers may mark their releases as unstable development versions (by inserting an underscore into the module version number which will also be reflected in the distribution name when you run 'make dist'), so the really hottest and newest distribution is not always the default. π
if a module Foo circulates on CPAN in both version 1.23 and 1.23_90, CPAN.pm offers a convenient way to install version 1.23 by saying
install Foo
this would install the complete distribution file (say BAR/Foo-1.23.tar.gz) with all accompanying material.
but if you would like to install version 1.23_90, you need to know where the distribution file resides on CPAN relative to the authors/id/ directory. if the author is BAR, this might be BAR/Foo-1.23_90.tar.gz; so you would have to say
install BAR/Foo-1.23_90.tar.gz
the first example will be driven by an object of the class CPAN::Module, the second by an object of class CPAN::Distribution. iykyk. π
ποΈ Integrating local directories
note: this feature is still in alpha state and may change in future versions of CPAN.pm.
Distribution objects are normally distributions from the CPAN, but there is a slightly degenerate case for Distribution objects, too, of projects held on the local disk. π₯οΈ
these distribution objects have the same name as the local directory and end with a dot. a dot by itself is also allowed for the current directory at the time CPAN.pm was used. all actions such as make, test, and install are applied directly to that directory. π―
this gives the command cpan . an interesting touch: while the normal mantra of installing a CPAN module without CPAN.pm is one of
perl Makefile.PL perl Build.PL
( go and get prerequisites )
make ./Build
make test ./Build test
make install ./Build install
the command cpan . does all of this at once. it figures out which of the two mantras is appropriate, fetches and installs all prerequisites, takes care of them recursively, and finally finishes the installation of the module in the current directory, be it a CPAN module or not. literally the multitasking queen. π
the typical usage case is for private modules or working copies of projects from remote repositories on the local disk. π
π Redirection
the usual shell redirection symbols | and > are recognized by the cpan shell only when surrounded by whitespace. so piping to pager or redirecting output into a file works somewhat as in a normal shell, with the stipulation that you must type extra spaces. yes, extra. spaces. bestie the spaces are load-bearing. π
π Plugin support EXPERIMENTAL
Plugins are objects that implement any of currently eight methods:
pre_get
post_get
pre_make
post_make
pre_test
post_test
pre_install
post_install
the plugin_list configuration parameter holds a list of strings of the form
Modulename=arg0,arg1,arg2,arg3,...
eg:
CPAN::Plugin::Flurb=dir,/opt/pkgs/flurb/raw,verbose,1
okay so at run time, each listed plugin gets instantiated as a singleton object β like, literally one (1) instance, that's the whole point β by running the equivalent of this pseudo code:
my $plugin = <string representation from config>;
<generate Modulename and arguments from $plugin>;
my $p = $instance{$plugin} ||= Modulename->new($arg0,$arg1,...);
the tea β: those generated singletons hang around from the instant they're created until the shell session ends. <plugin_list> can be reconfigured any time at run time, no restart era needed. While the cpan shell is running, it checks all activated plugins at each of the 8 reference points listed above and runs the respective method if it's implemented for that object. And that method gets called with the active CPAN::Distribution object passed in as an argument. slay. π
πΈ CONFIGURATION πΈ
The very first time the CPAN module is used, a configuration dialogue tries to figure out a couple of site specific options. The result of the dialog gets stored in a hash reference $CPAN::Config inside a file called CPAN/Config.pm. π«Ά
Default values defined in the CPAN/Config.pm file can be overridden in a user specific file: CPAN/MyConfig.pm. Best place to put that file is literally "$HOME/.cpan/CPAN/MyConfig.pm", because "$HOME/.cpan" is added to the search path of the CPAN module before the use() or require() statements. and the mkmyconfig command writes this file for you, so you don't even have to lift a finger π
.
If you want to keep your own CPAN/MyConfig.pm somewhere else, you should load it before loading CPAN.pm, like this:
perl -I/tmp/somewhere -MCPAN::MyConfig -MCPAN -eshell
--or--
perl -I/tmp/somewhere -MCPAN::MyConfig -S cpan
Once you're in the shell you can change your configuration like so. β¨
The o conf command has various bells and whistles, and honestly it's giving main character energy:
completion support
If you have a ReadLine module installed, you can hit Tab at any point of the commandline and o conf will offer you completion for the built-in subcommands and/or config variable names. iconic behavior honestly π
displaying some help: o conf help
Displays a short help. short and sweet, we love her πΈ
displaying current values: o conf [KEY]
Displays the current value(s) for this config variable. Without KEY, it displays all subcommands and config variables.
Example:
o conf shell
If KEY starts and ends with a slash, the string in between is treated as a regular expression and only keys matching this regexp get displayed π¦
Example:
o conf /color/
changing of scalar values: o conf KEY VALUE
Sets the config variable KEY to VALUE. The empty string can be specified as usual in shells, with '' or "" π
Example:
o conf wget /usr/bin/wget
changing of list values: o conf KEY SHIFT|UNSHIFT|PUSH|POP|SPLICE|LIST
If a config variable name ends with "list", it's a list, periodt. o conf KEY shift removes the first element of the list, o conf KEY pop removes the last element of the list. o conf KEYS unshift LIST prepends a list of values to the list, o conf KEYS push LIST appends a list of valued to the list.
Likewise, o conf KEY splice LIST passes the LIST to the corresponding splice command.
Finally, any other list of arguments is taken as a new list value for the KEY variable, discarding the previous value. out with the old, in with the new π¦
Examples:
o conf urllist unshift http://cpan.dev.local/CPAN
o conf urllist splice 3 1
o conf urllist http://cpan1.local http://cpan2.local ftp://ftp.perl.org
reverting to saved: o conf defaults
Reverts all config variables to the state in the saved config file. it's giving undo button π
saving the config: o conf commit
Saves all config variables to the current config file (CPAN/Config.pm or CPAN/MyConfig.pm that was loaded at start). bestie, don't forget this step or literally none of it sticks π
The configuration dialog can be started any time later again by issuing the command o conf init in the CPAN shell. And a subset of the configuration dialog can be run by issuing o conf init WORD where WORD is any valid config variable or a regular expression. so specific, so useful, obsessed π₯
π Config Variables π
The following keys in the hash reference $CPAN::Config are currently defined:
allow_installing_module_downgradesβ allow or disallow installing module downgrades. Like, do you really wanna go backwards? Your call, bestie πallow_installing_outdated_distsβ allow or disallow installing modules that are indexed in the cpan index pointing to a distro with a higher distro-version number πapplypatchβ path to external prgauto_commitβ commit all changes to config variables to disk πΎ (so your tweaks actually stick around, periodt)build_cacheβ size of cache for directories to build modulesbuild_dirβ locally accessible directory to build modulesbuild_dir_reuseβ boolean if distros in build_dir are persistentbuild_requires_install_policyβ to install or not to install when a module is only needed for building. Values areyes|no|ask/yes|ask/noπ§bzip2β path to external prgcache_metadataβ use serializer to cache metadatacheck_sigsβ if signatures should be verified πcleanup_after_installβ remove build directory immediately after a successful install and remember that for the duration of the session π§Ήcolorize_debugβTerm::ANSIColorattributes for debugging outputcolorize_outputβ boolean ifTerm::ANSIColorshould colorize output π (yes. the answer is yes.)colorize_printβTerm::ANSIColorattributes for normal outputcolorize_warnβTerm::ANSIColorattributes for warningscommandnumber_in_promptβ boolean if you want to see current command numbercommands_quoteβ preferred character to use for quoting external commands when running them. Defaults to double quote on Windows, single tick everywhere else; can be set to space to disable quotingconnect_to_internet_okβ whether to ask if opening a connection is ok beforeurllistis specifiedcpan_homeβ local directory reserved for this package πcurlβ path to external prgdontload_hashβDEPRECATEDπ like, do not use her, she's retireddontload_listβ arrayref: modules in the list will not be loaded by theCPAN::has_inst()routineftpβ path to external prgftp_passiveβ if set, the environment variableFTP_PASSIVEis set for downloadsftp_proxyβ proxy host for ftp requestsftpstats_periodβ max number of days to keep download statisticsftpstats_sizeβ max number of items to keep in the download statisticsgetcwdβ see below β¬οΈ (there's a whole-ahh section for this one)gpgβ path to external prggzipβ location of external programgziphalt_on_failureβ stop processing after the first failure of queued items or dependencies πhistfileβ file to maintain history between sessionshistsizeβ maximum number of lines to keep inhistfilehttp_proxyβ proxy host for http requestsinactivity_timeoutβ breaks interactiveMakefile.PLs orBuild.PLs after this many seconds inactivity. Set to0to disable timeouts.index_expireβ refetch index files after this many daysinhibit_startup_messageβ if true, suppress the startup message π€«keep_source_whereβ directory in which to keep the source (if we do)load_module_verbosityβ report loading of optional modules used byCPAN.pmlynxβ path to external prgmakeβ location of externalmakeprogrammake_argβ arguments that should always be passed to'make'make_install_make_commandβ the make command for running'make install', for example'sudo make'make_install_argβ same asmake_argfor'make install'makepl_argβ arguments passed to'perl Makefile.PL'mbuild_argβ arguments passed to'./Build'mbuild_install_argβ arguments passed to'./Build install'mbuild_install_build_commandβ command to use instead of'./Build'when we are in the install stage, for example'sudo ./Build'mbuildpl_argβ arguments passed to'perl Build.PL'ncftpβ path to external prgncftpgetβ path to external prgno_proxyβ don't proxy to these hosts/domains (comma separated list)pagerβ location of external programmore(or any pager)passwordβ your password if you CPAN server wants one π€« (yes, the manpage really says "you CPAN server", we keep the typos, it's canon)patchβ path to external prgpatches_dirβ local directory containing patch filesperl5lib_verbosityβ verbosity level forPERL5LIBadditionsplugin_listβ list of active hooks (see Plugin support above and theCPAN::Pluginmodule) πprefer_external_tarβ per default all untar operations are done withArchive::Tar; by setting this variable to true the externaltarcommand is used if availableprefer_installerβ legal values areMBandEUMM: if a module comes with both aMakefile.PLand aBuild.PL, use the former (EUMM) or the latter (MB); if the module comes with only one of the two, that one will be used no matter the setting βοΈprerequisites_policyβ what to do if you are missing module prerequisites ('follow'automatically,'ask'me, or'ignore'). For'follow', also setsPERL_AUTOINSTALLandPERL_EXTUTILS_AUTOINSTALLfor"--defaultdeps"if not already setprefs_dirβ local directory to store per-distro build optionsproxy_userβ username for accessing an authenticating proxyproxy_passβ password for accessing an authenticating proxypushy_httpsβ use https to cpan.org when possible, otherwise use http to cpan.org and issue a warning β οΈrandomize_urllistβ add some randomness to the sequence of theurllistπ²recommends_policyβ whether recommended prerequisites should be includedscan_cacheβ controls scanning of cache ('atstart','atexit'or'never')shellβ your favorite shell πshow_unparsable_versionsβ boolean ifrcommand tells which modules are versionlessshow_upload_dateβ boolean if commands should try to determine upload dateshow_zero_versionsβ boolean ifrcommand tells for which modules$version==0suggests_policyβ whether suggested prerequisites should be includedtarβ location of external programtartar_verbosityβ verbosity level for the tar commandterm_is_latinβ deprecated: if true Unicode is translated to ISO-8859-1 (and nonsense for characters outside latin range) π deprecated AND it produces nonsense, iconic honestlyterm_ornamentsβ boolean to turn ReadLine ornamenting on/offtest_reportβ email test reports (ifCPAN::Reporteris installed) π§trust_test_report_historyβ skip testing when previously tested ok (according toCPAN::Reporterhistory)unzipβ location of external programunzipurllistβ arrayref to nearby CPAN sites (or equivalent locations)urllist_ping_externalβ use external ping command when autoselecting mirrorsurllist_ping_verboseβ increase verbosity when autoselecting mirrorsuse_prompt_defaultβ setPERL_MM_USE_DEFAULTfor configure/make/test/installuse_sqliteβ useCPAN::SQLitefor metadata storage (fast and lean) β‘usernameβ your username if you CPAN server wants oneversion_timeoutβ stops version parsing after this many seconds. Default is15secs. Set to0to disable.wait_listβ arrayref to a wait server to try (SeeCPAN::WAIT)wgetβ path to external prgyaml_load_codeβ enable YAML code deserialisation viaCPAN::DeferredCodeyaml_moduleβ which module to use to read/write YAML files
You can set and query each of these options interactively in the cpan shell with the "o conf" or the "o conf init" command as specified below. π«Ά
"o conf <scalar option>"
prints the current value of the scalar option π
"o conf <scalar option> <value>"
Sets the value of the scalar option to value βοΈ
"o conf <list option>"
prints the current value of the list option in MakeMaker's neatvalue format. (yes, neatvalue, it's literally called that, we don't make the rules)
"o conf <list option> [shift|pop]"
shifts or pops the array in the list option variable
"o conf <list option> [unshift|push|splice] <list>"
works like the corresponding perl commands. fr fr, same energy π
interactive editing: o conf init [MATCH|LIST]
Runs an interactive configuration dialog for matching variables. Without argument runs the dialog over all supported config variables. To specify a MATCH the argument must be enclosed by slashes.
Examples:
o conf init ftp_passive ftp_proxy
o conf init /color/
Note: this method of setting config variables often provides more explanation about the functioning of a variable than the manpage. π (she's humble-bragging but she's right)
π§ CPAN::anycwd($path): Note on config variable getcwd
CPAN.pm changes the current working directory often and needs to determine its own current working directory. By default it uses Cwd::cwd, but if for some reason this doesn't work on your system, configure alternatives according to the following table:
cwdβ CallsCwd::cwdgetcwdβ CallsCwd::getcwdfastcwdβ CallsCwd::fastcwdgetdcwdβ CallsCwd::getdcwdbacktickcwdβ Calls the external commandcwd.
π Note on the format of the urllist parameter
urllist parameters are URLs according to RFC 1738. We do a little guessing if your URL is not compliant, but if you have problems with "file" URLs, please try the correct format. Either:
file://localhost/whatever/ftp/pub/CPAN/
or
file:///home/ftp/pub/CPAN/
πΏ The urllist parameter has CD-ROM support
The "urllist" parameter of the configuration table contains a list of URLs used for downloading. If the list contains any "file" URLs, CPAN always tries there first. This feature is disabled for index files. So the recommendation for the owner of a CD-ROM with CPAN contents is: include your local, possibly outdated CD-ROM as a "file" URL at the end of urllist, e.g.
o conf urllist push file://localhost/CDROM/CPAN
CPAN.pm will then fetch the index files from one of the CPAN sites that come at the beginning of urllist. It will later check for each module to see whether there is a local copy of the most recent version. π΅οΈββοΈβ¨
okay so another iconic little quirk of urllist: the site that we could successfully fetch the last file from automatically gets a preference token and is tried as the first site for the next request. so if you add a new site at runtime, it may happen that the previously preferred site will be tried another time. translation: if you want to disallow a site for the next transfer, it must be explicitly removed from urllist β no passive-aggressive side-eye, bestie, actually remove it. π
πΈ Maintaining the urllist parameter πΈ
if you have YAML.pm (or some other YAML module configured in yaml_module) installed, CPAN.pm collects a few statistical data about recent downloads. you can view the statistics with the hosts command or inspect them directly by looking into the FTPstats.yml file in your cpan_home directory. π
to get some interesting statistics, it is recommended that randomize_urllist be set; this introduces some amount of randomness into the URL selection. slay for load balancing, basically. π
π
The requires and build_requires dependency declarations π
since CPAN.pm version 1.88_51, modules declared as build_requires by a distribution are treated differently depending on the config variable build_requires_install_policy. here's the tea: by setting build_requires_install_policy to no, such a module is not installed. it is only built and tested, and then kept in the list of tested but uninstalled modules. as such, it is available during the build of the dependent module by integrating the path to the blib/arch and blib/lib directories in the environment variable PERL5LIB. if build_requires_install_policy is set to yes, then both modules declared as requires and those declared as build_requires are treated alike. by setting to ask/yes or ask/no, CPAN.pm asks the user and sets the default accordingly. π«Ά
π‘οΈ Configuration of the allow_installing_* parameters π‘οΈ
the allow_installing_* parameters are evaluated during the make phase. if set to yes, they allow the testing and the installation of the current distro and otherwise have no effect. if set to no, they may abort the build (preventing testing and installing), depending on the contents of the blib/ directory. quick reminder: the blib/ directory is the directory that holds all the files that would usually be installed in the install phase. π
allow_installing_outdated_distsβ compares theblib/directory with the CPAN index. if it finds something there that belongs, according to the index, to a different dist, it aborts the current build. πallow_installing_module_downgradesβ compares theblib/directory with already installed modules, actually their version numbers, as determined byExtUtils::MakeMakeror equivalent. if a to-be-installed module would downgrade an already installed module, the current build is aborted. π¨
an interesting twist occurs when a distroprefs document demands the installation of an outdated dist via goto while allow_installing_outdated_dists forbids it. without additional provisions, this would let the allow_installing_outdated_dists win and the distroprefs lose. so the proper arrangement in such a case is to write a second distroprefs document for the distro that goto points to and overrule the cpanconfig there. e.g.:
---
match:
distribution: "^MAUKE/Keyword-Simple-0.04.tar.gz"
goto: "MAUKE/Keyword-Simple-0.03.tar.gz"
---
match:
distribution: "^MAUKE/Keyword-Simple-0.03.tar.gz"
cpanconfig:
allow_installing_outdated_dists: yes
π§ Configuration for individual distributions (Distroprefs) π§
(note: this feature has been introduced in CPAN.pm 1.8854)
distributions on CPAN usually behave according to what we call the CPAN mantra. or since the advent of Module::Build we should talk about two mantras:
perl Makefile.PL perl Build.PL
make ./Build
make test ./Build test
make install ./Build install
but some modules cannot be built with this mantra. they try to get some extra data from the user via the environment, extra arguments, or interactively--thus disturbing the installation of large bundles like Phalanx100 or modules with many dependencies like Plagger.
the distroprefs system of CPAN.pm addresses this problem by allowing the user to specify extra info and recipes in YAML files to either
- pass additional arguments to one of the four commands,
- set environment variables
- instantiate an
Expectobject that reads from the console, waits for some regular expressions and enters some answers - temporarily override assorted
CPAN.pmconfiguration variables - specify dependencies the original maintainer forgot
- disable the installation of an object altogether
see the YAML and Data::Dumper files that come with the CPAN.pm distribution in the distroprefs/ directory for examples. π
π Filenames π
the YAML files themselves must have the .yml extension; all other files are ignored (for two exceptions see Fallback Data::Dumper and Storable below). the containing directory can be specified in CPAN.pm in the prefs_dir config variable. try o conf init prefs_dir in the CPAN shell to set and activate the distroprefs system. π
every YAML file may contain arbitrary documents according to the YAML specification, and every document is treated as an entity that can specify the treatment of a single distribution.
filenames can be picked arbitrarily; CPAN.pm always reads all files (in alphabetical order) and takes the key match (see below in Language Specs) as a hashref containing match criteria that determine if the current distribution matches the YAML document or not. π₯
π¦ Fallback Data::Dumper and Storable π¦
if neither your configured yaml_module nor YAML.pm is installed, CPAN.pm falls back to using Data::Dumper and Storable and looks for files with the extensions .dd or .st in the prefs_dir directory. these files are expected to contain one or more hashrefs. for Data::Dumper generated files, this is expected to be done by defining $VAR1, $VAR2, etc. the YAML shell would produce these with the command
ysh < somefile.yml > somefile.dd
for Storable files the rule is that they must be constructed such that Storable::retrieve(file) returns an array reference and the array elements represent one distropref object each. the conversion from YAML would look like so:
perl -MYAML=LoadFile -MStorable=nstore -e '
@y=LoadFile(shift);
nstore(\@y, shift)' somefile.yml somefile.st
in bootstrapping situations it is usually sufficient to translate only a few YAML files to Data::Dumper for crucial modules like YAML::Syck, YAML.pm and Expect.pm. if you prefer Storable over Data::Dumper, remember to pull out a Storable version that writes an older format than all the other Storable versions that will need to read them. π
π Blueprint π
the following example contains all supported keywords and structures with the exception of eexpect which can be used instead of expect. π
---
comment: "Demo"
match:
module: "Dancing::Queen"
distribution: "^CHACHACHA/Dancing-"
not_distribution: "\.zip$"
perl: "/usr/local/cariba-perl/bin/perl"
perlconfig:
archname: "freebsd"
not_cc: "gcc"
env:
DANCING_FLOOR: "Shubiduh"
disabled: 1
cpanconfig:
make: gmake
pl:
args:
- "--somearg=specialcase"
env: {}
expect:
- "Which is your favorite fruit"
- "apple\n"
make:
args:
- all
- extra-all
env: {}
expect: []
commandline: "echo SKIPPING make"
test:
args: []
env: {}
expect: []
install:
args: []
env:
WANT_TO_INSTALL: YES
expect:
- "Do you really want to install"
- "y\n"
patches:
- "ABCDE/Fedcba-3.14-ABCDE-01.patch"
depends:
configure_requires:
LWP: 5.8
build_requires:
Test::Exception: 0.25
requires:
Spiffy: 0.30
π§ Language Specs π§
every YAML document represents a single hash reference. the valid keys in this hash are as follows: β¨
comment[scalar]β a comment.cpanconfig[hash]β temporarily override assortedCPAN.pmconfiguration variables. supported are:build_requires_install_policy,check_sigs,make,make_install_make_command,prefer_installer,test_report. please report as a bug when you need another one supported. πdepends[hash]* EXPERIMENTAL FEATURE * β all three types, namelyconfigure_requires,build_requires, andrequiresare supported in the way specified in the META.yml specification. the current implementation merges the specified dependencies with those declared by the package maintainer. in a future implementation this may be changed to override the original declaration. πdisabled[boolean]β specifies that this distribution shall not be processed at all.features[array]* EXPERIMENTAL FEATURE * β experimental implementation to deal with optional_features from META.yml. still needs coordination with installer software and currently works only for META.yml declaringdynamic_config=0. use with caution. β οΈgoto[string]β the canonical name of a delegate distribution to install instead. useful when a new version, although it tests OK itself, breaks something else or a developer release or a fork is already uploaded that is better than the last released version. π―install[hash]β processing instructions for themake installor./Build installphase of the CPAN mantra. see below under Processing Instructions.make[hash]β processing instructions for themakeor./Buildphase of the CPAN mantra. see below under Processing Instructions.match[hash]β a hashref with one or more of the keysdistribution,module,perl,perlconfig, andenvthat specify whether a document is targeted at a specific CPAN distribution or installation. keys prefixed withnot_negates the corresponding match.- the corresponding values are interpreted as regular expressions. the
distributionrelated one will be matched against the canonical distribution name, e.g.AUTHOR/Foo-Bar-3.14.tar.gz. - the
modulerelated one will be matched against all modules contained in the distribution until one module matches. - the
perlrelated one will be matched against$^X(but with the absolute path).
- the corresponding values are interpreted as regular expressions. the
The value that hangs out with perlconfig is literally its own hashref, and it gets matched against the corresponding values in the %Config::Config hash chillin' inside the Config.pm module. And bestie β any key with a not_ prefix in front of it negates the match. Yes, it flips it. π©·
Same energy for env: its value is also its own hashref, matched against the corresponding values in the %ENV hash. Keys with a not_ prefix negate that match too.
Now, if you spec more than one restriction of module, distribution, etc., then the results of all those separately computed match values have to all match. If they do, the hashref that the YAML document represents gets returned as the preference structure for the current distribution. Slay. π
patches [array]
An array of patches, on CPAN or on your local disk, that get applied in order via an external patch program. Whether the value for the -p parameter is 0 or 1 is figured out by reading the patch beforehand. The path to each patch is either an absolute path on the local filesystem, or relative to a patch directory specified in the patches_dir configuration variable, or given in the format of a canonical distro name. For examples, go look at the distroprefs/ directory in the CPAN.pm distribution (heads up: those examples are not installed by default).
Note: if theapplypatchprogram is installed andCPAN::Configknows about it, and a patch was written by themakepatchprogram, thenCPAN.pmletsapplypatchapply that patch. Bothmakepatchandapplypatchare available from CPAN in theJV/makepatch-*distribution. π§
pl [hash]
Processing instructions for the perl Makefile.PL or perl Build.PL phase of the CPAN mantra. Peep below under Processing Instructions. β¨
test [hash]
Processing instructions for the make test or ./Build test phase of the CPAN mantra. Also below, under Processing Instructions. πΈ
Processing Instructions π
args [array]
Arguments to be added to the command line.
commandline
A full commandline to run via system(). While it's running, the environment variable PERL is set to $^X (but with an absolute path, bestie β absolute). If commandline is specified, then args is not used.
eexpect [hash]
Extended expect. This is a hash reference with four allowed keys: mode, timeout, reuse, and talk.
You must install the Expect module to use eexpect. CPAN.pm does not install it for you, so that's on you, babe. π
mode can have the values deterministic for when all the questions come in the order they're written down, and anyorder for when the questions may come in any order. The default mode is deterministic.
timeout means a timeout in seconds. Floating-point timeouts are OK. With mode=deterministic, the timeout is the timeout per question; with mode=anyorder it's the timeout per byte received from the stream or questions.
talk is a reference to an array containing alternating questions and answers. The questions are regular expressions and the answers are literal strings. The Expect module watches the stream from the execution of the external program (perl Makefile.PL, perl Build.PL, make, etc.).
For mode=deterministic, CPAN.pm injects the corresponding answer as soon as the stream matches the regular expression. β‘
For mode=anyorder, CPAN.pm answers a question as soon as the timeout is reached for the next byte in the input stream. In this mode you can use the reuse parameter to decide what happens to a question-answer pair after it's been used. In the default case (reuse=0) it's removed from the array, which keeps it from being used again by accident. So if you want to answer the question "Do you really want to do that" several times, it has to be in the array at least as many times as you want that answer given. Setting the parameter reuse to 1 makes that repetition unnecessary. π
env [hash]
Environment variables to be set during the command.
expect [array]
You must install the Expect module to use expect. Again: CPAN.pm does not install it for you. π
expect: <array> is just short notation for this eexpect:
eexpect:
mode: deterministic
timeout: 15
talk: <array>
Schema verification with Kwalify π
If you have the Kwalify module installed (which is part of the Bundle::CPANxxl), then all your distroprefs files get checked for syntactic correctness. Very demure, very mindful.
Example Distroprefs Files ποΈ
CPAN.pm ships with a whole collection of example YAML files. But real talk β these are really just examples and you should not use them without care, because they literally cannot fit everybody's purpose. The authors of the packages that ask questions had a need to ask, so you should watch their questions and adjust the examples to your environment and your needs. You have been warned:-) π
PROGRAMMER'S INTERFACE π©βπ»
If you do not enter the shell, shell commands are available both as methods (CPAN::Shell->install(...)) and as functions in the calling package (install(...)). Before you call low-level commands, it makes sense to initialize the components of CPAN you need, like this:
CPAN::HandleConfig->load;
CPAN::Shell::setup_output;
CPAN::Index->reload;
High-level commands do those initializations automatically, so don't stress. π«Ά
There's currently only one class with a stable interface β CPAN::Shell. All the commands available in the CPAN shell are methods of the class CPAN::Shell. The arguments on the commandline get passed as arguments to the method.
So if you take, for example, the shell command
notest install A B C
the command that actually gets executed is
CPAN::Shell->notest("install","A","B","C");
Each of the commands that produce listings of modules (r, autobundle, u) also returns a list of the IDs of all modules within the list. Free list, no cap. π
expand($type,@things)
The IDs of all objects available within a program are strings that can be expanded to the corresponding real objects with the CPAN::Shell->expand("Module",@things) method. Expand returns a list of CPAN::Module objects according to the @things arguments you gave it. In scalar context, it returns only the first element of the list.
expandany(@things)
Like expand, but it returns objects of the appropriate type β i.e. CPAN::Bundle objects for bundles, CPAN::Module objects for modules, and CPAN::Distribution objects for distributions. Note: it does not expand to CPAN::Author objects. Nope, not those. β
Programming Examples π
This is what lets you, the programmer, do operations that combine functionalities available in the shell.
# install everything that is outdated on my disk:
perl -MCPAN -e 'CPAN::Shell->install(CPAN::Shell->r)'
# install my favorite programs if necessary:
for $mod (qw(Net::FTP Digest::SHA Data::Dumper)) {
CPAN::Shell->install($mod);
}
# list all modules on my disk that have no VERSION number
for $mod (CPAN::Shell->expand("Module","/./")) {
next unless $mod->inst_file;
# MakeMaker convention for undefined $VERSION:
next unless $mod->inst_version eq "undef";
print "No VERSION in ", $mod->id, "\n";
}
# find out which distribution on CPAN contains a module:
print CPAN::Shell->expand("Module","Apache::Constants")->cpan_file
Or, if you wanna schedule a cron job to watch CPAN, you could list all the modules that need updating. First, the quick and dirty way:
perl -e 'use CPAN; CPAN::Shell->r;'
If you don't want any output when all the modules are up to date, parse the output of the above command for the regular expression /modules are up to date/ and decide to mail the output only if it doesn't match. Big brain move honestly. π§
If you'd rather do it more in a programmerish style, in one single process, something like this might suit you better:
# list all modules on my disk that have newer versions on CPAN
for $mod (CPAN::Shell->expand("Module","/./")) {
next unless $mod->inst_file;
next if $mod->uptodate;
printf "Module %s is installed as %s, could be updated to %s from CPAN\n",
$mod->id, $mod->inst_version, $mod->cpan_version;
}
If that gives you too much output every day, you might want to watch only three modules. You can write
for $mod (CPAN::Shell->expand("Module","/Apache|LWP|CGI/")) {
as the first line instead. Or you can combine some of the above tricks:
# watch only for a new mod_perl module
$mod = CPAN::Shell->expand("Module","mod_perl");
exit if $mod->uptodate;
# new mod_perl arrived, let me know all update recommendations
CPAN::Shell->r;
Methods in the other Classes πΈ
CPAN::Author::as_glimpse()β returns a one-line description of the author.CPAN::Author::as_string()β returns a multi-line description of the author.CPAN::Author::email()β returns the author's email address.CPAN::Author::fullname()β returns the author's name.CPAN::Author::name()β an alias forfullname.CPAN::Bundle::as_glimpse()β returns a one-line description of the bundle.CPAN::Bundle::as_string()β returns a multi-line description of the bundle.CPAN::Bundle::clean()β recursively runs thecleanmethod on all items contained in the bundle.CPAN::Bundle::contains()β returns a list of objects' IDs contained in a bundle. The associated objects may be bundles, modules or distributions.CPAN::Bundle::force($method,@args)β forces CPAN to perform a task that it normally would have refused to do. Force takes as arguments a method name to be called and any number of additional arguments that should be passed to the called method. The internals of the object get the needed changes so that CPAN.pm doesn't refuse to take the action. Theforceis passed recursively to all contained objects. See also the section above on theforceand thefforcepragma.CPAN::Bundle::get()β recursively runs thegetmethod on all items contained in the bundle.CPAN::Bundle::inst_file()β returns the highest installed version of the bundle in either@INCor$CPAN::Config->{cpan_home}. Note that this is different fromCPAN::Module::inst_file. πCPAN::Bundle::inst_version()β likeCPAN::Bundle::inst_file, but returns the$VERSION.CPAN::Bundle::uptodate()β returns1if the bundle itself and all its members are up-to-date.CPAN::Bundle::install()β recursively runs theinstallmethod on all items contained in the bundle.CPAN::Bundle::make()β runsmakerecursively on every single item living inside the bundle β¨CPAN::Bundle::readme()β recursively callsreadmeon all the items in the bundle πCPAN::Bundle::test()β recursively callsteston everything in the bundle π§CPAN::Distribution::as_glimpse()β hands you back a one-line description of the distribution πCPAN::Distribution::as_string()β same energy, but multi-line, so more room to vibe π¦CPAN::Distribution::authorβ returns theCPAN::Authorobject of the maintainer who uploaded this distribution πCPAN::Distribution::pretty_id()β returns a string shaped like"AUTHORID/TARBALL", where AUTHORID is the author's PAUSE ID and TARBALL is the distribution filename πΈCPAN::Distribution::base_id()β gives you the distribution filename with any archive suffix stripped off. E.g"Foo-Bar-0.01"πCPAN::Distribution::clean()β hops into the directory where the distribution got unpacked and runsmake cleanright there π§ΉCPAN::Distribution::containsmods()β returns a list of IDs of the modules contained in a distribution file. Heads up: it only works for distributions listed in the02packages.details.txt.gzfile, which typically means just the most recent version of a distribution is covered πCPAN::Distribution::cvs_import()β changes into the directory where the distribution was unpacked and runs something like this in there:
cvs -d $cvs_root import -m $cvs_log $cvs_dir $userid v$version
CPAN::Distribution::dir()β returns the directory that this distribution has been unpacked into πCPAN::Distribution::force($method,@args)β makes CPAN do a thing it would normally have flat-out refused to do π€ Force takes, as arguments, a method name to call plus any number of extra arguments that should get passed along to that method. The internals of the object get the needed changes so that CPAN.pm doesn't refuse to take the action. Also go peek at the section above on theforceand thefforcepragma πCPAN::Distribution::get()β downloads the distribution from CPAN and unpacks it. Does literally nothing if the distribution was already downloaded and unpacked within the current session π«ΆCPAN::Distribution::install()β changes into the directory where the distribution was unpacked and runs the external commandmake installin there. Ifmakehasn't been run yet, it gets run first. Amake testis issued in any case, and if that fails, the install is cancelled π The cancellation can be avoided by lettingforcerun theinstallfor you.
This install method only has the power to install the distribution if there are no dependencies in the way. To install an object along with all of its dependencies, use CPAN::Shell->install.
Note thatinstall()gives no meaningful return value. Seeuptodate(). π
CPAN::Distribution::isa_perl()β returns1if this distribution file seems to be a perl distribution. Normally that's derived from the file name only, but the index from CPAN can contain a hint to achieve a return value of true for other filenames too βCPAN::Distribution::look()β changes into the directory where the distribution was unpacked and opens a subshell there. Exiting the subshell returns you πCPAN::Distribution::make()β first runs thegetmethod to make sure the distribution is downloaded and unpacked. Then it changes into the directory where the distribution was unpacked and runs the external commandsperl Makefile.PLorperl Build.PLandmakein there π₯CPAN::Distribution::perldoc()β downloads the pod documentation of the file associated with a distribution (in HTML format) and runs it through the external command lynx specified in$CPAN::Config->{lynx}. If lynx isn't available, it converts it to plain text with the external command html2text and runs it through the pager specified in$CPAN::Config->{pager}πCPAN::Distribution::prefs()β returns the hash reference from the first matching YAML file that the user has deposited in theprefs_dir/directory. First succeeding match wins, periodt. The files in theprefs_dir/are processed alphabetically, and the canonical distro name (e.g.AUTHOR/Foo-Bar-3.14.tar.gz) is matched against the regular expressions stored in the$root->{match}{distribution}attribute value. On top of that, all module names contained in a distribution are matched against the regular expressions in the$root->{match}{module}attribute value. The two match values are ANDed together. Each of the two attributes is optional πCPAN::Distribution::prereq_pm()β returns the hash reference that a distribution announced as itsrequiresandbuild_requireselements. These can be declared either by theMETA.yml(if authoritative) or deposited after the run ofBuild.PLin the file./_build/prereqs, or after the run ofMakfile.PLwritten as thePREREQ_PMhash in a comment in the producedMakefile. Note: this method only works after an attempt has been made tomakethe distribution. Returns undef otherwise π«CPAN::Distribution::readme()β downloads the README file associated with a distribution and runs it through the pager specified in$CPAN::Config->{pager}πCPAN::Distribution::reports()β downloads report data for this distribution from www.cpantesters.org and displays a subset of them πCPAN::Distribution::read_yaml()β returns the content of the META.yml of this distro as a hashref. Note: works only after an attempt has been made tomakethe distribution. Returns undef otherwise. Also returns undef if the content of META.yml is not authoritative. (The rules about what exactly makes the content authoritative are still in flux, bestie β nobody's decided yet πͺοΈ)CPAN::Distribution::test()β changes into the directory where the distribution was unpacked and runsmake testright there π§ͺCPAN::Distribution::uptodate()β returns1if all the modules contained in the distribution are up-to-date. It relies on containsmods π―CPAN::Index::force_reload()β forces a reload of all indices π€CPAN::Index::reload()β reloads all indices if they have not been read for more than$CPAN::Config->{index_expire}days β°CPAN::InfoObj::dump()βCPAN::Author,CPAN::Bundle,CPAN::Module, andCPAN::Distributionall inherit this method. It prints the data structure associated with an object. Super useful for debugging π
Note: the data structure is considered internal and thus subject to change without notice. Don't get attached π
CPAN::Module::as_glimpse()β returns a one-line description of the module in four columns: the first column contains the wordModule, the second column is one character β an equals sign if this module is already installed and up-to-date, a less-than sign if this module is installed but can be upgraded, and a space if the module is not installed. The third column is the name of the module, and the fourth column gives maintainer or distribution information πCPAN::Module::as_string()β returns a multi-line description of the module π¦CPAN::Module::clean()β runs a clean on the distribution associated with this module π§ΉCPAN::Module::cpan_file()β returns the filename on CPAN that's associated with the module πCPAN::Module::cpan_version()β returns the latest version of this module available on CPAN π₯CPAN::Module::cvs_import()β runs a cvs_import on the distribution associated with this module πΏCPAN::Module::description()β returns a 44 character description of this module. Only available for modules listed in The Module List (CPAN/modules/00modlist.long.htmlor00modlist.long.txt.gz) πCPAN::Module::distribution()β returns theCPAN::Distributionobject that contains the current version of this module πCPAN::Module::dslip_status()β returns a hash reference. The keys of the hash are the letters"D","S","L","I", and <P>, for development status, support level, language, interface and public licence respectively. The data for the DSLIP status gets collected by pause.perl.org when authors register their namespaces. The values of the 5 hash elements are one-character words whose meaning is described in the table below. There are also 5 hash elements"DV","SV","LV","IV", and <PV> that carry a more verbose value of the 5 status variables β¨
Where the 'DSLIP' characters have the following meanings:
Dβ Development Stage (Note: NO IMPLIED TIMESCALES):iβ Idea, listed to gain consensus or as a placeholdercβ under construction but pre-alpha (not yet released)a/bβ Alpha/Beta testingRβ ReleasedMβ Mature (no rigorous definition)Sβ Standard, supplied with Perl 5
Sβ Support Level:mβ Mailing-listdβ Developeruβ Usenet newsgroup comp.lang.perl.modulesnβ None known, try comp.lang.perl.modulesaβ abandoned; volunteers welcome to take over maintenance
Lβ Language Used:pβ Perl-only, no compiler needed, should be platform independentcβ C and perl, a C compiler will be neededhβ Hybrid, written in perl with optional C code, no compiler needed+β C++ and perl, a C++ compiler will be neededoβ perl and another language other than C or C++
Iβ Interface Stylefβ plain Functions, no references usedhβ hybrid, object and function interfaces availablenβ no interface at all (huh?)rβ some use of unblessed References or tiesOβ Object oriented using blessed references and/or inheritance
Pβ Public Licensepβ Standard-Perl: user may choose between GPL and Artisticgβ GPL: GNU General Public Licenselβ LGPL: "GNU Lesser General Public License" (previously known as "GNU Library General Public License")bβ BSD: The BSD Licenseaβ Artistic license alone2β Artistic license 2.0 or lateroβ open source: approved by www.opensource.orgdβ allows distribution without restrictionsrβ restricted distributionnβ no license at all
okay so the CPAN::Module method lineup keeps going, and honestly? iconic behavior only:
CPAN::Module::force($method,@args)β forces CPAN to do a task it would normally refuse to do. It takes a method name to invoke plus any number of extra arguments to pass to that method. The internals of the object get the needed changes so CPAN.pm doesnβt refuse the action. See also the section above on the"force"and the"fforce"pragma.CPAN::Module::get()β runs ageton the distribution associated with this module.CPAN::Module::inst_file()β returns the filename of the module found in@INC. The first file found is what gets reported, just like perl itself stops searching@INConce it finds a module.CPAN::Module::available_file()β returns the filename of the module found inPERL5LIBor@INC. The first file found is reported. Its flex overinst_fileis that modules that have been tested but not yet installed are included, becausePERL5LIBkeeps track of tested modules. slay.CPAN::Module::inst_version()β returns the version number of the installed module in readable format.CPAN::Module::available_version()β returns the version number of the available module in readable format.CPAN::Module::install()β runs aninstallon the distribution associated with this module.CPAN::Module::look()β changes to the directory where the distribution associated with this module has been unpacked and opens a subshell there. Exiting the subshell returns.CPAN::Module::make()β runs amakeon the distribution associated with this module.CPAN::Module::manpage_headline()β if the module is installed, peeks into the moduleβs manpage, reads the headline, and returns it. And if the module has been downloaded within this session, it does the equivalent on the downloaded module even if it hasnβt been installed yet. obsessed.CPAN::Module::perldoc()β runs aperldocon this module.CPAN::Module::readme()β runs areadmeon the distribution associated with this module.CPAN::Module::reports()β calls thereports()method on the associated distribution object.CPAN::Module::test()β runs ateston the distribution associated with this module.CPAN::Module::uptodate()β returns1if the module is installed and up-to-date.CPAN::Module::userid()β returns the authorβs ID of the module.
π§Ί Cache Manager π§Ί
Currently the cache manager only keeps track of the build directory ($CPAN::Config->{build_dir}). Itβs a simple FIFO mechanism that deletes complete directories below build_dir as soon as the size of all directories there gets bigger than $CPAN::Config->{build_cache} (in MB). The contents of this cache may be used for later re-installations that you intend to do manually, but they will never be trusted by CPAN itself. Why? Because the user might use these directories for building modules on different architectures. no cap.
Thereβs another directory ($CPAN::Config->{keep_source_where}) where the original distribution files are kept. This directory is not covered by the cache manager and must be controlled by the user. If you choose to have the same directory as build_dir and as keep_source_where directory, then your sources will be deleted with the same fifo mechanism. so maybe donβt do that unless youβre feeling spicy.
π Bundles π
A bundle is just a perl module in the namespace Bundle:: that does not define any functions or methods. It usually only contains documentation. itβs giving βlookbook, not logic.β
It starts like a perl module with a package declaration and a $VERSION variable. After that the pod section looks like any other pod, with the only difference being that one special pod section exists starting with (verbatim):
=head1 CONTENTS
In this pod section each line obeys the format
Module_Name [Version_String] [- optional text]
The only required part is the first field, the name of a module (e.g. Foo::Bar, i.e. not the name of the distribution file). The rest of the line is optional. The comment part is delimited by a dash just as in the man page header.
The distribution of a bundle should follow the same convention as other distributions.
Bundles are treated specially in the CPAN package. If you say 'install Bundle::Tkkit' (assuming such a bundle exists), CPAN will install all the modules in the CONTENTS section of the pod. You can install your own Bundles locally by placing a conformant Bundle file somewhere into your @INC path. The autobundle() command which is available in the shell interface does that for you by including all currently installed modules in a snapshot bundle file. bestie bundle behavior.
π± PREREQUISITES π±
The CPAN program is trying to depend on as little as possible so the user can use it in hostile environment. It works better the more goodies the environment provides. For example if you try in the CPAN shell
install Bundle::CPAN
or
install Bundle::CPANxxl
you will find the shell more convenient than the bare shell before.
If you have a local mirror of CPAN and can access all files with file: URLs, then you only need a perl later than perl5.003 to run this module. Otherwise Net::FTP is strongly recommended. LWP may be required for non-UNIX systems, or if your nearest CPAN site is associated with a URL that is not ftp:.
If you have neither Net::FTP nor LWP, there is a fallback mechanism implemented for an external ftp command or for an external lynx command. backup plan icon behavior.
π§° UTILITIES π§°
π Finding packages and VERSION π
This module presumes that all packages on CPAN
- declare their
$VERSIONvariable in an easy to parse manner. This prerequisite can hardly be relaxed because it consumes far too much memory to load all packages into the running program just to determine the$VERSIONvariable. Currently all programs that are dealing with version use something like this:
perl -MExtUtils::MakeMaker -le \
'print MM->parse_version(shift)' filename
If you are author of a package and wonder if your $VERSION can be parsed, please try the above method.
- come as compressed or gzipped tarfiles or as zip files and contain a
Makefile.PLorBuild.PL(well, we try to handle a bit more, but with little enthusiasm).
π Debugging π
Debugging this module is more than a bit complex due to interference from the software producing the indices on CPAN, the mirroring process on CPAN, packaging, configuration, synchronicity, and even (gasp!) due to bugs within the CPAN.pm module itself. itβs a whole ecosystem, bestie.
For debugging the code of CPAN.pm itself in interactive mode, some debugging aid can be turned on for most packages within CPAN.pm with one of
o debug package...β sets debug mode for packages.o debug -package...β unsets debug mode for packages.o debug allβ turns debugging on for all packages.o debug numberβ which sets the debugging packages directly. Note thato debug 0turns debugging off.
What seems a successful strategy is the combination of reload cpan and the debugging switches. Add a new debug statement while running in the shell and then issue a reload cpan and see the new debugging messages immediately without losing the current context. main character debugging moment.
o debug without an argument lists the valid package names and the current set of packages in debugging mode. o debug has built-in completion support.
For debugging of CPAN data there is the dump command which takes the same arguments as make/test/install and outputs each objectβs Data::Dumper dump. If an argument looks like a perl variable and contains one of $, @ or %, it is eval()ed and fed to Data::Dumper directly.
πΎ Floppy, Zip, Offline Mode πΎ
CPAN.pm works nicely without network access, too. If you maintain machines that are not networked at all, you should consider working with file: URLs. Youβll have to collect your modules somewhere first. So you might use CPAN.pm to put together all you need on a networked machine. Then copy the $CPAN::Config->{keep_source_where} (but not $CPAN::Config->{build_dir}) directory on a floppy. This floppy is kind of a personal CPAN. CPAN.pm on the non-networked machines works nicely with this floppy. See also below the paragraph about CD-ROM support. offline era, but make it cute.
π οΈ Basic Utilities for Programmers π οΈ
has_inst($module)β returns true if the module is installed. Used to load all modules into the running CPAN.pm that are considered optional. The config variabledontload_listintercepts thehas_inst()call such that an optional module is not loaded despite being available. For example, the following command will preventYAML.pmfrom being loaded:
cpan> o conf dontload_list push YAML
See the source for details.
use_inst($module)β similar tohas_inst(), tries to load optional library but also dies if library is not available.has_usable($module)β returns true if the module is installed and in a usable state. Only useful for a handful of modules that are used internally. See the source for details.instance($module)β the constructor for all the singletons used to represent modules, distributions, authors, and bundles. If the object already exists, this method returns the object; otherwise, it calls the constructor.frontend(),frontend($new_frontend)β getter/setter for frontend object. Method just allows to subclass CPAN.pm.
π SECURITY π
real talk: thereβs no strong security layer in CPAN.pm. CPAN.pm helps you to install foreign, unmasked, unsigned code on your machine.
We compare to a checksum that comes from the net just as the distribution file itself. But we try to make it easy to add security on demand:
π Cryptographically signed modules π
Since release 1.77, CPAN.pm has been able to verify cryptographically signed module distributions using Module::Signature. The CPAN modules can be signed by their authors, thus giving more security. The simple unsigned MD5 checksums that were used before by CPAN protect mainly against accidental file corruption.
You will need to have Module::Signature installed, which in turn requires that you have at least one of Crypt::OpenPGP module or the command-line gpg tool installed.
You will also need to be able to connect over the Internet to the public key servers, like pgp.mit.edu, and their port 11731 (the HKP protocol).
The configuration parameter check_sigs is there to turn signature checking on or off. security toggle unlocked.
π¦ EXPORT π¦
Most functions in package CPAN are exported by default. The reason for this is that the primary use is intended for the cpan shell or for one-liners. lowkey convenient, highkey intentional.
β¨ ENVIRONMENT β¨
So CPAN does a lil juggling act with environment variables behind your back and you should lowkey know about it π
- When the CPAN shell enters a subshell via the
lookcommand, it sets the environment variableCPAN_SHELL_LEVELto1, or increments that variable if it's already set. Recursion tracking, bestie πͺ - When CPAN runs, it sets the environment variable
PERL5_CPAN_IS_RUNNINGto the ID of the running process. It also setsPERL5_CPANPLUS_IS_RUNNINGto prevent runaway processes which could happen with older versions ofModule::Install. Safety first π - When running
perl Makefile.PL, the environment variablePERL5_CPAN_IS_EXECUTINGis set to the full path of theMakefile.PLthat is being executed. This prevents runaway processes with newer versions ofModule::Install. - When the config variable
ftp_passiveis set, all downloads will be run with the environment variableFTP_PASSIVEset to this value. This is in general a good idea as it influences bothNet::FTPand LWP based connections. The same effect can be achieved by starting the cpan shell with this environment variable set. ForNet::FTPalone, one can also always set passive mode by runninglibnetcfg.
π POPULATE AN INSTALLATION WITH LOTS OF MODULES π
Okay so you just installed a fresh perl and you want all your fave modules in it? Honestly so easy if you maintain a private bundle definition file, bestie π
To get a useful blueprint of a bundle definition file, the command autobundle can be used on the CPAN shell command line. This command writes a bundle definition file for all modules installed for the current perl interpreter. It's recommended to run this command once only, and from then on maintain the file manually under a private name, say Bundle/my_bundle.pm. With a clever bundle file you can then simply say
cpan> install Bundle::my_bundle
then answer a few questions and go out for coffee (possibly even in a different city) ββ¨ iconic behaviour tbh.
Now, maintaining a bundle definition file means keeping track of two things: dependencies and interactivity. CPAN.pm sometimes fails on calculating dependencies because not all modules define all MakeMaker attributes correctly, so a bundle definition file should specify prerequisites as early as possible. On the other hand, it's annoying that so many distributions need some interactive configuring. So what you can try to accomplish in your private bundle file is to have the packages that need to be configured early in the file and the gentle ones later, so you can go out for coffee after a few minutes and leave CPAN.pm to churn away unattended π«Ά
π₯ WORKING WITH CPAN.pm BEHIND FIREWALLS π₯
Thanks to Graham Barr for contributing the following paragraphs about the interaction between perl, and various firewall configurations π For further information on firewalls, it is recommended to consult the documentation that comes with the ncftp program. If you are unable to go through the firewall with a simple Perl setup, it's likely that you can configure ncftp so that it works through your firewall.
π§± Three basic types of firewalls
Firewalls can be categorized into three basic types, bestie. Buckle up π’
π http firewall
This is when the firewall machine runs a web server, and to access the outside world, you must do so via that web server. If you set environment variables like http_proxy or ftp_proxy to values beginning with http://, or in your web browser you've proxy information set, then you know you are running behind an http firewall.
To access servers outside these types of firewalls with perl (even for ftp), you need LWP or HTTP::Tiny.
π‘ ftp firewall
This where the firewall machine runs an ftp server. This kind of firewall will only let you access ftp servers outside the firewall. This is usually done by connecting to the firewall with ftp, then entering a username like user@outside.host.com.
To access servers outside these type of firewalls with perl, you need Net::FTP.
π«₯ One-way visibility
One-way visibility means these firewalls try to make themselves invisible to users inside the firewall. An FTP data connection is normally created by sending your IP address to the remote server and then listening for the return connection. But the remote server will not be able to connect to you because of the firewall. For these types of firewall, FTP connections need to be done in a passive mode π΄
There are two that I can think off.
𧦠SOCKS
If you are using a SOCKS firewall, you will need to compile perl and link it with the SOCKS library. This is what is normally called a 'socksified' perl π With this executable you will be able to connect to servers outside the firewall as if it were not there. Slay.
π IP Masquerade
This is when the firewall implemented in the kernel (via NAT, or networking address translation), it allows you to hide a complete network behind one IP address. With this firewall no special compiling is needed as you can access hosts directly.
For accessing ftp servers behind such firewalls you usually need to set the environment variable FTP_PASSIVE or the config variable ftp_passive to a true value.
π± Configuring lynx or ncftp for going through a firewall
If you can go through your firewall with e.g. lynx, presumably with a command such as
/usr/local/bin/lynx -pscott:tiger
then you would configure CPAN.pm with the command
o conf lynx "/usr/local/bin/lynx -pscott:tiger"
That's all. Similarly for ncftp or ftp, you would configure something like
o conf ncftp "/usr/bin/ncftp -f /home/scott/ncftplogin.cfg"
Your mileage may vary... π
π¬ FAQ π¬
The crowd goes wild, the questions are extremely real, let's go π
- I installed a new version of module X but CPAN keeps saying, I have the old version installed
Probably you do have the old version installed. This can happen if a module installs itself into a different directory in the @INC path than it was previously installed. This is not really a CPAN.pm problem, you would have the same problem when installing the module manually. The easiest way to prevent this behaviour is to add the argument UNINST=1 to the make install call, and that is why many people add this argument permanently by configuring
o conf make_install_arg UNINST=1
- So why is
UNINST=1not the default?
Because there are people who have their precise expectations about who may install where in the @INC path and who uses which @INC array. In fine tuned environments UNINST=1 can cause damage π¬
- I want to clean up my mess, and install a new perl along with all modules I have. How do I go about it?
Run the autobundle command for your old perl and optionally rename the resulting bundle file (e.g. Bundle/mybundle.pm), install the new perl with the Configure option prefix, e.g.
./Configure -Dprefix=/usr/local/perl-5.6.78.9
Install the bundle file you produced in the first step with something like
cpan> install Bundle::mybundle
and you're done. Periodt π
- When I install bundles or multiple modules with one command there is too much output to keep track of.
You may want to configure something like
o conf make_arg "| tee -ai /root/.cpan/logs/make.out"
o conf make_install_arg "| tee -ai /root/.cpan/logs/make_install.out"
so that STDOUT is captured in a file for later inspection π΅οΈββοΈ
- I am not root, how can I install a module in a personal directory?
As of CPAN 1.9463, if you do not have permission to write the default perl library directories, CPAN's configuration process will ask you whether you want to bootstrap <local::lib>, which makes keeping a personal perl library directory easy β¨
Another thing you should bear in mind is that the UNINST parameter can be dangerous when you are installing into a private area because you might accidentally remove modules that other people depend on that are not using the private area. Be careful, bestie β οΈ
- How to get a package, unwrap it, and make a change before building it?
Have a look at the look (!) command π
- I installed a Bundle and had a couple of fails. When I retried, everything resolved nicely. Can this be fixed to work on first try?
The reason for this is that CPAN does not know the dependencies of all modules when it starts out. To decide about the additional items to install, it just uses data found in the META.yml file or the generated Makefile. An undetected missing piece breaks the process. But it may well be that your Bundle installs some prerequisite later than some depending item and thus your second try is able to resolve everything. Please note, CPAN.pm does not know the dependency tree in advance and cannot sort the queue of things to install in a topologically correct order π It resolves perfectly well if all modules declare the prerequisites correctly with the PREREQ_PM attribute to MakeMaker or the requires stanza of Module::Build. For bundles which fail and you need to install often, it is recommended to sort the Bundle definition file manually.
- In our intranet, we have many modules for internal use. How can I integrate these modules with CPAN.pm but without uploading the modules to CPAN?
Have a look at the CPAN::Site module π’
- When I run CPAN's shell, I get an error message about things in my
/etc/inputrc(or~/.inputrc) file.
These are readline issues and can only be fixed by studying readline configuration on your architecture and adjusting the referenced file accordingly. Please make a backup of the /etc/inputrc or ~/.inputrc and edit them. Quite often harmless changes like uppercasing or lowercasing some arguments solves the problem π§
- Some authors have strange characters in their names.
Internally CPAN.pm uses the UTF-8 charset. If your terminal is expecting ISO-8859-1 charset, a converter can be activated by setting term_is_latin to a true value in your config file. One way of doing so would be
cpan> o conf term_is_latin 1
If other charset support is needed, please file a bug report against CPAN.pm at rt.cpan.org and describe your needs. Maybe we can extend the support or maybe UTF-8 terminals become widely available π
Note: this config variable is deprecated and will be removed in a future version of CPAN.pm. It will be replaced with the conventions around the family of$LANGand$LC_*environment variables.
- When an install fails for some reason and then I correct the error condition and retry, CPAN.pm refuses to install the module, saying "Already tried without success".
You could use the force pragma like so
force install Foo::Bar
Or, if you wanna dodge the whole force install thing (which, reminder, installs even when the tests fail π), you can force just the test and then install normally:
force test Foo::Bar
install Foo::Bar
Or honestly just:
look Foo::Bar
and then run make install right there in the subshell. easy π
- How do I install a "DEVELOPER RELEASE" of a module?
By default CPAN grabs the latest non-developer release of a module. If you actually want the dev release, you gotta spell out the partial path starting with the author id, pointing at the tarball you want, like this:
cpan> install KWILLIAMS/Module-Build-0.27_07.tar.gz
Small note: the ls command will list that path for you if you need it. π«Ά
- How do I install a module and all its dependencies from the commandline, without being prompted for anything, despite my CPAN configuration (or lack thereof)?
CPAN asks its questions through ExtUtils::MakeMaker's prompt() function, so if you set the PERL_MM_USE_DEFAULT environment variable, you shouldn't get asked anything at all (assuming the modules you're installing are nice enough to respect that variable too):
% PERL_MM_USE_DEFAULT=1 perl -MCPAN -e 'install My::Module'
- How do I create a Module::Build based Build.PL derived from an ExtUtils::MakeMaker focused Makefile.PL?
http://search.cpan.org/dist/Module-Build-Convert/ β that's the one, bestie β¨
- I'm frequently irritated with the CPAN shell's inability to help me select a good mirror.
Good news, CPAN can now help you pick a "good" mirror, based on which ones have the lowest 'ping' round-trip times. From the shell, just run the command o conf init urllist and let CPAN automatically pick mirrors for you. π
Past that assist, the urllist config parameter is all yours β add and remove sites whenever you want. You should figure out which sites have the best up-to-dateness, bandwidth, reliability, etc., and which ones are topologically close to you. Some people want fast downloads, some want up-to-dateness, some want reliability. You decide which to try in which order.
Henk P. Penning maintains a site that collects data about CPAN sites:
Also, go nuts with experimental features. Run
o conf init randomize_urllist ftpstats_period ftpstats_size
and pick your fave parameters. After a few downloads, running the hosts command will probably help you choose the best mirror sites. β
- Why do I get asked the same questions every time I start the shell?
Because your changes aren't saved yet, babe π Make them permanent by calling the command o conf commit. Or set the auto_commit variable to true by running o conf init auto_commit and answering the next question with yes.
- Older versions of CPAN.pm had the original root directory of all tarballs in the build directory. Now there are always random characters appended to these directory names. Why was this done?
Those random characters come from File::Temp and they make sure each module's individual build directory is unique. Which means running CPAN.pm in concurrent processes at the same time is safe. iconic behaviour, honestly π
- Speaking of the build directory. Do I have to clean it up myself?
Your call! You can set the config variable scan_cache to never β but then yeah, you're cleaning it up yourself. The other possible values, atstart and atexit, clean up the build directory when you start (or more precisely, after the first extraction into the build directory) or when you exit the CPAN shell, respectively. And if you never start up the CPAN shell at all, you probably have to clean up the build directory yourself too. π
- How can I switch to sudo instead of local::lib?
Five environment variables need to be reset to their previous values: PATH, PERL5LIB, PERL_LOCAL_LIB_ROOT, PERL_MB_OPT, PERL_MM_OPT. And two CPAN.pm config variables must be reconfigured: make_install_make_command and mbuild_install_build_command. The five env variables have probably been overwritten in your $HOME/.bashrc or some equivalent. So you either find them there, delete their traces, and log out/log in β or you override them temporarily, depending on your exact desire. The two cpanpm config variables can be set with:
o conf init /install_.*_command/
probably followed by
o conf commit
- How do
recommends_policyandsuggests_policywork, exactly?
The terms "recommends" and "suggests" have been standardized in https://metacpan.org/pod/CPAN::Meta::Spec πΈ
In CPAN.pm, if you set recommands_policy to a true value, that means: if you then install a distribution "Foo" that recommends a module "Bar", both "Foo" and "Bar" will be tested and potentially installed.
Similarly, if you set suggests_policy to a true value, it means: if you install a distribution "Foo" that suggests a module "Bar", both "Foo" and "Bar" will be tested and potentially installed.
In either case, when "Foo" passes its tests and "Bar" does not pass its tests, "Foo" will be installed nontheless. But if "Foo" does not pass its tests, neither will be installed.
This also works recursively for all recommends and suggests of the module "Bar".
This has also been illustrated by a cpan tester, who wrote:
I just tested Starlink-AST-3.03 which recommends Tk::Zinc; Tk-Zinc-3.306 fails with http://www.cpantesters.org/cpan/report/a2de7c38-810d-11ee-9ad4-e2167316189a ; nonetheless Starlink-AST-3.03 succeeds with http://www.cpantesters.org/cpan/report/9352e754-810d-11ee-90e9-46117316189a
π COMPATIBILITY π
OLD PERL VERSIONS
CPAN.pm is regularly tested to run under 5.005 and assorted newer versions. But ngl, it's getting more and more difficult to get the minimal prerequisites working on older perls. Getting the whole Bundle::CPAN working there is close to impossible. So if you're in the position of only having these old versions, heads up: CPAN is designed to work fine without the Bundle::CPAN installed. π
To get things going, note that GBARR/Scalar-List-Utils-1.18.tar.gz is compatible with ancient perls, and that File::Temp is listed as a prerequisite but CPAN has reasonable workarounds if it's missing.
CPANPLUS
This module and its competitor, the CPANPLUS module, are both much cooler than the other. CPAN.pm is older. CPANPLUS was designed to be more modular, but it was never intended to be compatible with CPAN.pm.
CPANMINUS
In the year 2010 App::cpanminus was launched as a new approach to a cpan shell with a considerably smaller footprint. Very cool stuff. π₯
π SECURITY ADVICE π
This software enables you to upgrade software on your computer and so is inherently dangerous, because the newly installed software may contain bugs and may alter the way your computer works or even make it unusable. Please consider backing up your data before every upgrade. fr fr, back it up. π
π BUGS π
Please report bugs via http://rt.cpan.org/
Before submitting a bug, please make sure that the traditional method of building a Perl module package from a shell by following the installation instructions of that package still works in your environment.
π AUTHOR π
Andreas Koenig <andk@cpan.org>
π LICENSE π
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See http://www.perl.com/perl/misc/Artistic.html
πΈ TRANSLATIONS πΈ
Kawai,Takanori provides a Japanese translation of a very old version of this manpage at http://homepage3.nifty.com/hippo2000/perltips/CPAN.htm
π¦ SEE ALSO π¦
Lots of people enter the CPAN shell by running the cpan utility program, which is installed in the same directory as perl itself. So if you have this directory in your PATH variable (or some equivalent in your operating system), then typing cpan in a console window will work for you too. On top of that, the utility provides several commandline shortcuts. β¨
melezhik (Alexey) sent me a link where he published a chef recipe to work with CPAN.pm: http://community.opscode.com/cookbooks/cpan.
aaaand that's a wrap bestie π«Ά this whole thing is from perl v5.42.3, dated 2026-11-03, and it's the CPAN(3pm) page β go forth, install modules, and back up your data first, mwah ππ
π¦ where this page comes from
- alpine 3.24: perl-doc 5.42.3-r0 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms