POD2::P...cal::lib(3)
🌸 NAME 🌸
Okay so bestie, welcome to POD2::P...cal::lib(3) — that's the Perl-docs-section-3 manual page for local::lib~[pt_br], which is just the Brazilian Portuguese translation of local::lib, and it does literally one iconic thing: it creates and uses a local lib/ directory for perl modules, using PERL5LIB. That's the whole assignment. ✨
🎀 SINOPSE 🎀
In code, like this:
use local::lib; # configura um lib local em ~/perl5
use local::lib '~/foo'; # idem, mas ~/foo
# Ou...
use FindBin;
use local::lib "$FindBin::Bin/../suporte"; # bibliotecas de suporte locais à aplicação
From the command line (shell), like this:
# Instala o LWP e suas dependências não encontradas no diretório '~/perl5'
perl -MCPAN -Mlocal::lib -e 'CPAN::install(LWP)'
# Apenas exibe alguns comandos úteis para a shell
$ perl -Mlocal::lib
export PERL_MB_OPT='--install_base /home/username/perl5'
export PERL_MM_OPT='INSTALL_BASE=/home/username/perl5'
export PERL5LIB='/home/username/perl5/lib/perl5/i386-linux:/home/username/perl5/lib/perl5'
export PATH="/home/username/perl5/bin:$PATH"
Quick note, no cap: the comments inside these examples are in Portuguese, because this is the ~[pt_br] edition. We're keeping them exactly as-is. 💅
🧚 A técnica de 'bootstrapping'
A super common way to install local::lib is using what everyone calls the "bootstrapping" technique. It's a genuinely good approach when your sysadmin hasn't installed local::lib. In that case, you'll need to install local::lib in your own user directory.
Even if you do have admin privileges, you should still set up your environment variables, as discussed in step 4 below. Without them, you'll still be installing modules into the system CPAN, and your Perl scripts won't use the lib/ path you set with local::lib. So like… do step 4 anyway, bestie. 🫶
By default, local::lib installs CPAN modules — and itself — in ~/perl5.
Windows users should read "Diferenças ao usar esse módulo em Win32" (that section is right down there ⬇️).
- Download and unpack
local::libfrom CPAN (look for "Download" on the CPAN page aboutlocal::lib). Do this as a normal user, not as root or administrator. Unpack the file in your user directory or any other convenient location. - Run this:
perl Makefile.PL --bootstrap
If the system asks whether it should configure everything it can automatically, you probably should answer yes.
To install local::lib in a directory other than the default, you'll need to specify it when calling bootstrap, like this:
perl Makefile.PL --bootstrap=~/foo
- Run this: (
local::libassumes you have themakecommand installed on your system)
make test && make install
- Now we need to set up the appropriate environment variables so Perl uses our freshly created
lib/directory. If you're using bash or another Bourne shell, you can do it by adding this line to your shell startup script:
echo 'eval $(perl -I$HOME/perl5/lib/perl5 -Mlocal::lib)' >>~/.bashrc
If you're using the C shell, you can do it like this:
/bin/csh
echo $SHELL
/bin/csh
perl -I$HOME/perl5/lib/perl5 -Mlocal::lib >> ~/.cshrc
If you passed bootstrap a directory that isn't the default, you'll need to point at it in the local::lib call, like this:
echo 'eval $(perl -I$HOME/foo/lib/perl5 -Mlocal::lib=$HOME/foo)' >>~/.bashrc
After updating your shell config file, make sure you process it again so you get the changes in your current shell. Bourne shells use . ~/.bashrc for that, while C shells use source ~/.cshrc.
If you're on a slow machine or working with big disk space limitations, you can turn off automatic manpage generation from POD when installing modules. For that, just pass the --no-manpages argument during bootstrap:
perl Makefile.PL --bootstrap --no-manpages
To avoid having to do several bootstraps for several Perl module environments on the same user account — for example if you use local::lib to develop different independent applications — you can use a single bootstrap installation of local::lib to install modules in different directories like this:
cd ~/meudir1
perl -Mlocal::lib=./
eval $(perl -Mlocal::lib=./) ### Para configurar o ambiente apenas nessa shell
printenv ### Veja que o ~/meudir1 está na PERL5LIB
perl -MCPAN -e install ... ### Os módulos que quiser
cd ../meudir2
... REPITA ...
For multiple environments meant for multiple applications, you may need to include a modified version of the use FindBin instructions in the "No código" example above. If you did something like what was described above, you'll have a set of Perl modules in ~/meudir1/lib. If you have a script at ~/meudir1/scripts/meuscript.pl, you'll need to tell it where to find the modules you installed for it in ~/meudir1/lib.
In ~/meudir1/scripts/meuscript.pl:
use strict;
use warnings;
use local::lib "$FindBin::Bin/.."; ### aponta para ~/meudir1 e o local::lib acha o lib/
use lib "$FindBin::Bin/../lib"; ### aponta para ~/meudir1/lib
Put this before any BEGIN { ... } block that needs the installed modules. Order matters, bestie, the interpreter reads top-down. 💀
🪟 Diferenças ao usar esse módulo em Win32
To set up the appropriate environment variables for your current CMD.exe session, you can do it like this:
C:\>perl -Mlocal::lib
set PERL_MB_OPT=--install_base C:\DOCUME~1\ADMINI~1\perl5
set PERL_MM_OPT=INSTALL_BASE=C:\DOCUME~1\ADMINI~1\perl5
set PERL5LIB=C:\DOCUME~1\ADMINI~1\perl5\lib\perl5;C:\DOCUME~1\ADMINI~1\perl5\lib\perl5\MSWin32-x86-multi-thread
set PATH=C:\DOCUME~1\ADMINI~1\perl5\bin;%PATH%
### Para configurar o ambiente apenas dessa shell
C:\>perl -Mlocal::lib > %TEMP%\tmp.bat && %TEMP%\tmp.bat && del %TEMP%\temp.bat
### em vez de $(perl -Mlocal::lib=./)
If you want the environment settings to persist, you'll need to add them in Control Panel -> System, or use App::local::lib::Win32Helper.
~ gets turned into the user profile directory (the directory named after the user inside Documents and Settings (Windows XP or earlier) or Usuários (Windows Vista and more recent)) unless $ENV{HOME} exists. After that, the directory name is shortened and the subdirectories are created (which means the directory must exist). 🫡
💜 MOTIVAÇÃO 💜
The version of a Perl package on your machine isn't always the one you need. Obviously, the best thing to do would be to update it to the version you want. However, you might be in a situation that stops you from doing that. Maybe you don't have system administrator privileges; or maybe you're on a package management system like Debian's, and a package at your desired version just doesn't exist yet.
local::lib solves this problem by making it possible to create your own directory of Perl packages pulled from CPAN (on multi-user systems, that usually lives inside your user directory). The system's Perl installation stays completely unchanged; you just call Perl with special options so it uses the packages in your local directory instead of the system ones. local::lib arranges things so that locally installed versions of the Perl packages take precedence over the system's. 👑
If you're using a package management system (like on Debian systems), you don't need to worry about conflicts between Debian and CPAN. Your local version of the packages gets installed in a completely different directory from the versions installed by the system's package manager. Two separate lanes, no drama. 🌈
✨ DESCRIÇÃO ✨
This module gives you a fast and convenient way to create a user-local module repository inside the user's own directory. It also assembles and displays for the user a list of environment variables using the syntax of the user's current shell (as specified by the SHELL environment variable), all ready to be dropped straight into the shell config file. It's giving "just copy-paste it, babe". 💅
Broadly speaking, local::lib lets you create and use a directory containing Perl modules outside Perl's @INC. That makes it easy to build applications with a specific version of a given module, or a whole collection of modules. It's also useful when a module's maintainer hasn't applied a certain patch you need for your application.
During import, local::lib sets appropriate values for the following environment variables:
PERL_MB_OPTPERL_MM_OPTPERL5LIBPATH— values get appended toPATH, instead of replacing it.
Those values are then available for reference by any other code after the import. 🎀
🦋 CRIANDO UM CONJUNTO AUTO-CONTIDO DE MÓDULOS 🦋
See lib::core::only for a way to do this — but note that there are a whole bunch of caveats to that approach, and the best way is always to do the 'build' against a clean version of perl (i.e. with 'site' and 'vendor' as empty as possible). Srsly, clean room energy only. 🧼
✨ MÉTODOS ✨
Okay so, agora vem a parte que faz o corre acontecer: os métodos. Vou listar todos na ordem, com argumentos e retorno, sem deixar nada cair no esquecimento. 💅
🛠️ ensure_dir_structure_for
- Argumentos:
$caminho_do_diretorio - Valor de Retorno: Nenhum
Ela tenta criar o caminho que você passou e todos os diretórios superiores necessários. Se falhar, solta uma exceção — tipo, sem drama extra, só falha mesmo. 😭
📢 print_environment_vars_for
- Argumentos:
$caminho_do_diretorio - Valor de Retorno: Nenhum
Cospe na saída padrão as variáveis listadas acima, devidamente ajustadas pra usar o caminho fornecido como diretório base. Printou, tá ligado? ✨
🧪 build_environment_vars_for
- Argumentos:
$caminho_do_diretorio,$interpolar - Valor de Retorno:
%variaveis_de_ambiente
Retorna um hash com as variáveis de ambiente listadas acima, devidamente ajustadas pra usar o caminho fornecido como diretório base. Os argumentos são $caminho_do_diretorio e $interpolar, fr fr. 🧬
🧷 setup_env_hash_for
- Argumentos:
$caminho_do_diretorio - Valor de Retorno: Nenhum
Constrói as chaves no %ENV pro caminho fornecido, chamando build_environment_vars_for. É tipo um atalho chique, iykyk. 🫶
📚 install_base_perl_path
- Argumentos:
$caminho_do_diretorio - Valor de Retorno:
$caminho_base_de_instalacao
Retorna um caminho de diretório indicando onde instalar os módulos Perl pra essa instalação local de bibliotecas. Adiciona os diretórios "lib" e "perl5" ao final do caminho fornecido. Slay de organização. 🎀
🏗️ install_base_arch_path
- Argumentos:
$caminho_do_diretorio - Valor de Retorno:
$caminho_base_de_instalacao_arch
Retorna um caminho de diretório indicando onde instalar os módulos Perl de arquiteturas específicas pra essa instalação local de bibliotecas. Baseia-se no valor de retorno do método install_base_perl_path, adicionando o valor de $Config{archname}. Arquitetura entrou no chat. 🦋
🛣️ install_base_bin_path
- Argumentos:
$caminho_do_diretorio - Valor de Retorno:
$caminho_base_de_instalacao_bin
Retorna um caminho de diretório indicando onde instalar programas executáveis pra essa instalação local de bibliotecas. Baseia-se no valor de retorno do método install_base_perl_path, adicionando o diretório "bin". Binário com glitter. ✨
🏠 resolve_empty_path
- Argumentos:
$caminho_do_diretorio - Valor de Retorno:
$caminho_base_de_instalacao
Cria e retorna o caminho de diretório raiz em que a instalação local de módulos deve ser feita. O padrão é "~/perl5". Casa do Perl, basicamente. 🏡
🧭 resolve_home_path
- Argumentos:
$caminho_do_diretorio - Valor de Retorno:
$caminho_para_home
Procura pelo diretório padrão (home) do usuário. Gera uma exceção caso não encontre resultado definitivo. Se não achar, é caos e exceção. 💀
🔁 resolve_relative_path
- Argumentos:
$caminho_do_diretorio - Valor de Retorno:
$caminho_absoluto
Transforma o caminho fornecido em um caminho absoluto. Nada de caminho perdido, bestie. 🌈
🧩 resolve_path
- Argumentos:
$caminho_do_diretorio - Valor de Retorno:
$caminho_absoluto
Invoca os seguintes métodos em sequência, passando o resultado do método anterior pro seguinte, na tentativa de descobrir onde configurar o ambiente pra instalação local de bibliotecas: resolve_empty_path, resolve_home_path, resolve_relative_path. Passa o caminho de diretório fornecido pra resolve_empty_path, que retorna um resultado que é passado pra resolve_home_path, que então tem seu resultado passado pra resolve_relative_path. O resultado dessa chamada final é então retornado pelo resolve_path. Pipeline de resolver, puro glamour. 👑
⚠️ UM AVISO SOBRE UNINST=1
Tenha cuidado ao usar o local::lib em conjunto commake install UNINST=1. A ideia dessa opção é desinstalar a versão anterior de um módulo antes de instalar a mais recente. No entanto ela não possui uma verificação de segurança de que a versão antiga e a nova referem-se ao mesmo diretório. Usada em combinação com o local::lib, você pode potencialmente apagar uma versão globalmente acessível de um módulo e instalar a versão mais nova no diretório local. Apenas utilizemake install UNINST=1junto com o local::lib se você entende essas possíveis consequências. É giving arriscado, então vai com calma. 😭
🚧 LIMITAÇÕES
- As ferramentas auxiliares do perl não conseguem lidar com nomes de diretórios contendo espaços, então não é possível fazer seu bootstrap do local::lib em um diretório com espaços. O que você pode fazer é mover seu local::lib pra um diretório com espaços após ter instalado todos os módulos dentro dele. Mas esteja ciente que você não poderá atualizar ou instalar outros módulos do CPAN nesse diretório local após a mudança. Espaços: o inimigo do rolê. 💀
- A detecção da shell é relativamente básica. Neste momento, qualquer coisa com
cshno nome será tratada como a C shell ou compatível, e todo o resto será tratado como Bourne, exceto em sistemas Win32. Caso a variável de ambienteSHELLnão esteja disponível, assumiremos tratar-se de uma shell compatível com a Bourne. Tipo assim: detecção lowkey simples. 🐚 - A técnica de bootstrap é um hack e usará o CPAN.pm pro ExtUtils::MakeMaker mesmo que você tenha o CPANPLUS instalado. Hack com carinha de feature. 🙈
- Destrói qualquer valor pré-existente nas variáveis de ambiente
PERL5LIB,PERL_MM_OPTePERL_MB_OPT. Não é drill, é aviso mesmo. ⚠️ - Provavelmente deveria auto-configurar o CPAN caso isso ainda não tenha sido feito. Provavelmente, sim. ✨
- Correções (patches) são muito bem-vindos pra quaisquer dos itens acima. Patches são o amor. 🫶
- Em sistemas Win32, não há uma forma de escrever no registro as variáveis de ambiente criadas, pra que elas persistam a uma reinicialização. Win32 e o reboot: um drama. 😭
🔧 SOLUÇÃO DE PROBLEMAS
Se você configurou o local::lib pra instalar módulos do CPAN em algum lugar do seu 'home', e mais tarde tentou instalar um módulo fazendo cpan -i Foo::Bar, mas ele falhou com um erro como: Warning: You do not have permissions to install into /usr/lib64/perl5/site_perl/5.8.8/x86_64-linux at /usr/lib64/perl5/5.8.8/Foo/Bar.pm e em algum lugar no seu log de instalação houver um erro dizendo 'INSTALL_BASE' is not a known MakeMaker parameter name, então você de alguma forma perdeu seu ExtUtils::MakeMaker atualizado. Plot twist: o MakeMaker sumiu. 💀
Pra remediar a situação, execute novamente o procedimento de bootstrap descrito acima.
Então, execute rm -r ~/.cpan/build/Foo-Bar*
Finalmente, execute novamente o cpan -i Foo::Bar e ele deve instalar sem problemas. Respira, dá certo. ✨
🌱 AMBIENTE
🐚 SHELL e COMSPEC
O local::lib procura pela variável de ambiente SHELL do usuário ao processar e exibir os comandos a serem adicionados no arquivo de configuração da shell.
Em sistemas Win32, COMSPEC também será examinado. Shell detectada, comandos prontos. 🦋
💬 SUPORTE
IRC: acesse #local-lib em irc.perl.org. Entra no chat, bestie. 🫶
🌍 AUTOR DA TRADUÇÃO
Breno G. de Oliveira, "<garu at cpan.org>", após ter perdido uma aposta pro Getty <http://search.cpan.org/~getty/> durante a Copa de 2010. Perdeu a aposta, mas entregou a tradução. 😭
©️ COPYRIGHT
Copyright (c) 2007 - 2010 "AUTHOR" in local::lib e "CONTRIBUTORS" in local::lib do local::lib como listados em local::lib. Créditos dados, sem cap. ✨
📜 LICENÇA
Esta biblioteca é software livre e pode ser distribuída sob os mesmos termos do perl. Livre, aberta e pronta pro corre. 💖
E é isso, bestie: essa página é do perl v5.42.0, com data 2023-08-07. Agora vai lá instalar teus módulos e brilhar. 👑✨💅
📦 where this page comes from
- opensuse-leap 16.0: perl-local-lib 2.000029-bp160.1.11 · Artistic-1.0 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