Perl installing modules linux

Конфигурирование и подгрузка модулей Perl в Linux

Данную заметку меня побудили написать определённые сложности при выполнении одиночного скрипта на языке Perl. Казалось бы, интерпретатор языка уже установлен – бери и пользуйся. Да не тут то было. Хочу избавить других от грабель, по которым я ходил целый вечер.

Начну с того, что Perl построен по модульной архитектуре и для тех или иных целей эти модули должны быть подгружены и сконфигурированы. В интернете вроде бы полно рекомендаций как это сделать, но почему-то упускается самое важное – необходимость компиляции и линковки, поскольку установка модулей Perl – это, зачастую, сборка из исходников.

На серверах же в их минималистичных вариантах ничего подобного не установлено, поэтому, пользуясь многочисленными «готовыми» интернет-решениями, можно долго ругаться от того, что на экран вываливается масса текстовой диагностики, но в результате ничего по этим рецептам не устанавливается и мы получаем в конце концов FAIL. Так поначалу было и в моём случае.

Требовалось запустить скрипт, который обращался к библиотеке модулей LPW, да ещё и работал по SSL. При попытке запуска я получил сообщение о невозможности определить местоположение модуля UserAgent.pm, который нужен для работы с WWW и который спокойно себе лежал по указанным в переменной @INC перловым путям. С этих странностей, собственно, всё и началось. Пришлось изрядно попотеть, чтобы разобраться в том, как подгружать и настраивать модули Perl.

Итак, отталкиваясь от того, что Perl-у для установки своих модулей нужны cc, make и иже с ними, сделаем предварительную подготовку системы, чтобы всё прошло гладко. Установим необходимые пакеты для компиляции из исходников и подгрузим библиотеки для сборки программ с поддержкой SSL:

#apt-get install make gcc libssl-dev #для дистрибутивов на базе Debian
#yum install make gcc openssl-dev #для дистрибутивов на базе Red-Hat

Теперь обновим установочный менеджер самого Perl. Он называется cpan.

С ним можно работать как в интерактивном режиме, так и в режиме однострочных команд.

Запуском команды cpan мы перейдём в интерактивный режим и позволим менеджеру сконфигурировать рабочее окружение Perl в автоматическом режиме, отвечая на все приглашения «yes». По завершении обновим сам менеджер:

#cpan install CPAN
#cpan reload cpan

Вот теперь можно приступать к установке необходимых библиотек модулей.

#cpan> install LWP
#cpan> install Bundle::LWP
#cpan> install HTTP::Protocol::https

Все исходные коды устанавливаемых вами модулей скачиваются из репозитория CPAN (www.cpan.org), помещаются в каталог /root/.cpan/build/ и представлены в виде папок с названиями этих пакетов, например, LWP-Protocol-https-6.06-0, где последняя цифра, своего рода, номер неудачной попытки сборки модуля. Сколько раз вы попытаетесь его собрать, столько и будет создано однотипных папок с практически одинаковым содержимым.

В процессе установки из менеджера cpan происходит активное тестирование пакета с помощью множества тестов, некоторые из которых по тем или иным причинам могут закончиться неудачно.
И если хотя бы один тест не будет пройден, вы получите сообщение о том, что модуль не создан.

Само собой, лучше, чтобы все тесты были пройдены, однако это не всегда критично и можно собрать модуль самостоятельно, минуя тестирование. Для этого следует перейти в соответствующую папку пакета /root/.cpan/build/package-X и поочерёдно выполнить команды:

#perl Makefile.PL
#make
#make install

Вероятность успешной сборки и загрузки модуля в боевой режим очень велика, хотя при работе целых фреймворков на Perl могут появиться жалобы на неудовлетворённые зависимости и т.п.

Читайте также:  Драйвер для принтера canon mf3200 для windows 10 64 bit

После завершения сборки Perl сам раскидает результат по правильным путям независимо от того, как и откуда выполнялась сборка (можно самостоятельно скачать исходники с www.cpan.org и запустить сборку из любой папки), поэтому, в принципе, папку /root/.cpan/ можно удалить, а занимает она порой немало места (в моём случае 87 Мб).

Вот, собственно, и всё, что я хотел сказать.

Источник

🐧 Как установить Perl-модули на Linux

В этом кратком руководстве мы покажем, как установить модули Perl в Linux из репозитория CPAN (Comprehensive Perl Archive Network).

На момент написания данного руководства в CPAN было доступно 185128 модулей Perl.

Многие программы, написанные на языке программирования Perl, зависят от определенных модулей Perl для выполнения конкретной задачи.

Например, на днях я тестировал Sysadmin-util, который предоставляет набор полезных инструментов для системных администраторов Linux / Unix:

Когда я тестировал определенный инструмент под названием multi-ping, я столкнулся со следующей ошибкой:

Установим модули Perl на Linux

Существует множество инструментов для установки и модулей Perl.

Мы собираемся попробовать два инструмента, а именно cpan и cpanm.

Стоит отметить, что для многих модулей на CPAN требуется последняя версия Perl 5.8 или выше.

Убедитесь, что вы установили пакет «make» в свой дистрибутив Linux.

«Make» – важный инструмент для создания Perl-модулей.

Если вы не устанавливаете «make», вы можете столкнуться с ошибкой, подобной приведенной ниже:

Пакет make доступен в репозиториях по умолчанию в большинстве дистрибутивов Linux.

Чтобы установить «make» в Arch Linux и его вариантах, запустите:

На Debian, Ubuntu, Linux Mint:

На Fedora:

На RHEL, CentOS:

На SUSE/openSUSE:

Установим модули Perl, используя cpan

cpan является клиентом командной строки для репозитория CPAN и по умолчанию распространяется со всеми версиями Perl.

Чтобы установить модуль Perl, например Net :: DNS, введите в оболочку cpan команду:

После установки модуля введите «exit», чтобы вернуться в свою оболочку.

Вы также можете напрямую установить модуль из Терминала с помощью команды:

Установим модули Perl, используя Cpanminus

Cpanminus или cpanm – это клиент cpan для получения, распаковки, сборки и установки модулей из репозитория CPAN.

Это автономный скрипт без зависимостей, который требует нулевой настройки.

Многие опытные разработчики Perl предпочитают cpanm нежели cpan.

Cpanminus может быть установлен разными способами.

1. Используя Perl:

Чтобы установить последнюю версию cpanm в вашей системе Linux, просто запустите:

2. Используя менеджер пакетов дистрибутива:

cpanm также доступен в репозиториях по умолчанию нескольких дистрибутивов Linux.

Это стабильная версия, но немного старая.

Чтобы установить cpanminus на Arch Linux и его вариантах, запустите:

На Debian, Ubuntu, Linux Mint:

3. Ручная установка:

Кроме того, вы можете вручную загрузить последний двоичный файл cpanm и поместить его в ваш $PATH, как показано ниже.

Пример вывода:

Установим отсутствующие модули Perl с помощью менеджера пакетов дистрибутива

Многие модули Perl доступны в виде пакетов, поэтому вы можете установить их с помощью диспетчера пакетов вашего дистрибутива.

На Debian, Ubuntu:

Чтобы найти отсутствующий модуль в Arch Linux, запустите:

Список установленных модулей Perl

Чтобы просмотреть список установленных модулей Perl, используйте команду «perldoc»:

Вывод:

Вы увидите следующий вывод:

В командной строке введите «l» для просмотра списка модулей.

Обратите внимание, что две вышеуказанные команды приведут список модулей, установленных с помощью cpan.

Там может быть много модулей, установленных вручную или предварительно установленных с вашим дистрибутивом Linux.

Чтобы найти все установленные модули Perl, запустите:

Удалим модули Perl

Модули Perl могут быть легко удалены с помощью cpanm с помощью команды:

Источник

Comprehensive Perl Archive Network

You can never have too many Perl modules

How to install CPAN modules

Here are some recommended approaches to installing modules from CPAN, as with much of Perl there are several alternatives.

Some basics

Most Perl modules are written in Perl, some use XS (they are written in C) so require a C compiler (it’s easy to get this setup — don’t panic), see your OS of choice below to find out how to get the right compiler. Modules may have dependencies on other modules (almost always on CPAN) and cannot be installed without them (or without a specific version of them). It is worth throughly reading the documentation for the options below. Many modules on CPAN require a somewhat recent version of Perl (version 5.8 or above).

Читайте также:  Оптимизация жесткого диска для windows 10

Quick start

Install cpanm to make installing other modules easier (you’ll thank us later). You need to type these commands into a Terminal emulator (Mac OS X, Win32, Linux)

Now install any module you can find.

Tools

To help you install and manage your modules:

local::lib enables you to install modules into a specified directory, without requiring root or administrator access. See the bootstrapping technique for how to get started. You can create a directory per user/project/company and deploy to other servers, by copying the directory (as long as you are on the same operating system and perl version).

cpanm from App::cpanminus is a script to get, unpack, build and install modules from CPAN. It’s dependency free (can bootstrap itself) and requires zero configuration (install instructions). It automates the entire build process for the majority of modules on CPAN and works well with local::lib and perlbrew. Many experienced Perl developers use this as their tool of choice. Related tools: cpan-outdated, pm-uninstall, cpan-listchanges.

perlbrew from App::perlbrew is useful if your system perl is too old to support modern CPAN modules, or if it’s troublesome in other capacities (RedHat/CentOS are included in this list). perlbrew makes the process of installing a Perl in any directory much easier, so that you can work completely independently of any system Perl without needing root or administrator privileges. You can use multiple versions of Perl (maybe as you upgrade) across different projects. The separation from your system Perl makes server maintenance much easier and you more confident about how your project is setup. Currently Windows is not supported.

cpan from CPAN has been distributed with Perl since 1997 (5.004). It has many more options than cpanm, it is also much more verbose.

cpanp from CPANPLUS had been distributed with Perl since 5.10 (2007) until 5.20 (2014). This offers even more options than cpanm or cpan and can be installed just like cpanminus.

Perl on Windows (Win32 and Win64)

Strawberry Perl is an open source binary distribution of Perl for the Windows operating system. It includes a compiler and pre-installed modules that offer the ability to install XS CPAN modules directly from CPAN. It also comes with lots of modules pre-installed, including cpanm.

ActiveState provide a binary distribution of Perl (for many platforms), as well as their own perl package manager (ppm). Some modules are not available as ppm’s or have reported errors on the ppm build system, this does not mean they do not work. You can use the cpan script to build modules from CPAN against ActiveState Perl.

Perl on Mac OSX

OSX comes with Perl pre-installed. in order to build and install your own modules you will need to install the «Command Line Tools for XCode» or «XCode» package — details on our ports page. Once you have done this you can use all of the tools mentioned above.

Perl on other Unix like OSs

Install ‘make’ through your package manager. You can then use all of the tools mentioned above.

Other tools

CPAN::Mini can provide you with a minimal mirror of CPAN (just the latest version of all modules). This makes working offline easy.

Читайте также:  Linux cpu frequency scaling

CPAN::Mini::Inject allows you to add your own modules to your local CPAN::Mini mirror of CPAN. So you can install and deploy your own modules through the same tools you use for CPAN modules.

Which modules should I use?

Task::Kensho lists suggested best practice modules for a wide range of tasks. https://metacpan.org/ will let you search CPAN. You could also get involved with the community, ask on a mailing list or find your nearest Perl Mongers group.

Yours Eclectically, The Self-Appointed Master Librarians (OOK!) of the CPAN.
© 1995-2010 Jarkko Hietaniemi. © 2011-2017 Perl.org. All rights reserved. Disclaimer.

Master mirror hosted by and

Источник

Perl installing modules linux

2nd February 2017 / Category: Tutorials / Comments: None

CPAN or also known as Comprehensive Perl Archive Network is a repository for modules written in Perl. Currently, there are 177,000+ published modules which can be downloaded and used by the Perl software developers or by the system/network administrators. Today we are going to show you how to install Perl modules manually or by using CPAN on your Linux.

Manual Perl module installation

There are different ways for installing Perl modules. One of the ways is by building the module from source. This way is useful when a single module with no dependencies is required to be installed. First of all, install the Perl language and the dependencies if they are not already installed on your server.

Once the required software is installed, go to http://search.cpan.org/ and search the module you would like to install. Let’s say you would like to install the DBD::mysql module. Download and unpack the source:

Build and install the Perl module using the following commands:

And that’s it. The module has been successfully installed. Please note that this way of installing Perl modules is not recommended as during the installation no dependencies are being installed. In other words, if the module has dependencies it will not work and you will need to manually install all of them to fix this. Alternatively, you can use your system package manager to install the module and all its dependencies automatically or use the cpan command.

Install Perl modules using CPAN

The CPAN perl module should already be installed on your Linux cloud server by default. In case it is not installed, go ahead and install it. To run cpan you can use the following command:

If this is the first time you are using cpan you will need to proceed with the basic configuration by answering a few simple questions.

The basic syntax for installing modules is the following:

To install the same Perl module we installed before you can use the following command:

This will also ensure that all module dependencies will be properly installed.

For more installation options as well as basic usage of the module you can check the module’s page at http://search.cpan.org/. For example, the page for the module we installed would be http://search.cpan.org/dist/DBD-mysql/lib/DBD/mysql/INSTALL.pod.

To learn how to interact with CPAN from the command line you can visit the cpan help page using the command below:

Of course, you don’t have to do any of this if you use one of our Linux Cloud VPS Hosting services, in which case you can simply ask our expert Linux admins to install any Perl module for you. They are available 24×7 and will take care of your request immediately.

PS. If you liked this post please share it with your friends on the social networks using the buttons on the left or simply leave a reply below. Thanks.

Источник

Оцените статью