fbpx

Comandos Linux – Comando perl

Visão geral do comando Linux perl

Sobre perl

O comando perl é o intérprete da linguagem de programação Perl .

Descrição

“Perl” significa oficialmente “Extração prática e linguagem de relatório”. Era originalmente um idioma otimizado para verificar arquivos de texto arbitrários , extrair informações desses arquivos e imprimir relatórios com base nessas informações. Ele rapidamente se tornou uma boa linguagem para muitas tarefas de gerenciamento do sistema. Ao longo dos anos, o Perl se tornou uma linguagem de programação de uso geral. É amplamente utilizado para tudo, desde o rápido “one-liners” até o desenvolvimento de aplicativos em grande escala .

O idioma deve ser prático (fácil de usar, eficiente, completo) e não bonito (minúsculo, elegante, minimalista). Ele combina alguns dos melhores recursos do sed , awk e sh , tornando familiar e fácil o uso dos usuários do Unix para criar soluções rápidas para problemas irritantes. Suas instalações de programação de uso geral suportam paradigmas de programação processual, funcional e orientada a objetos, tornando o Perl uma linguagem confortável para grandes projetos.

As raízes de Perl no processamento de texto não foram esquecidas ao longo dos anos. Ele ainda possui algumas das expressões regulares mais poderosas encontradas em qualquer lugar, e seu suporte para texto Unicode é de classe mundial. Também lida com todos os tipos de texto estruturado, através de uma extensa coleção de extensões. Essas bibliotecas , coletadas no CPAN , fornecem soluções prontas para uma variedade impressionante de problemas.

O lema do Perl é “Há mais de uma maneira de fazer isso”.

Executando o interpretador Perl

A maneira normal de executar um programa Perl é torná-lo diretamente executável ou passando o nome do arquivo de origem como argumento na linha de comando . (Um ambiente Perl interativo também é possível.) Na inicialização, o Perl procura seu programa em um dos seguintes locais:

  1. Linha especificada por linha via -e ou -E alterna na linha de comando.
  2. Contido no arquivo especificado pelo primeiro nome do arquivo na linha de comando. (Observe que os sistemas que suportam a notação #!, Como bash , chamam intérpretes dessa maneira.)
  3. Passado implicitamente via entrada padrão . Isso funciona apenas se não houver argumentos de nome de arquivo – para passar argumentos para um programa de leitura STDIN, você deve especificar explicitamente um ”  ” para o nome do programa.

Nos métodos 2 e 3, o Perl começa a analisar o arquivo de entrada desde o início, a menos que você tenha especificado uma opção -x ; nesse caso, ele procura a primeira linha começando com #! e contendo a palavra ” perl ” e começa lá. Isso é útil para executar um programa incorporado em uma mensagem maior. (Nesse caso, você indicaria o final do programa usando o token __END__ .)

#! A linha é sempre examinada em busca de opções à medida que a linha está sendo analisada . Portanto, se você estiver em uma máquina que permita apenas um argumento com o #! linha, ou pior, nem reconhece o #! linha, você ainda pode obter um comportamento consistente da opção, independentemente de como o Perl foi chamado, mesmo que -x tenha sido usado para encontrar o início do programa.

Porque historicamente alguns sistemas operacionais silenciosamente cortada do kernel interpretação do #! linha após 32 caracteres , algumas opções podem ser passadas na linha de comando e outras não; você pode até obter um ”  ” sem a letra, se não tomar cuidado. Você provavelmente quer ter certeza de que todos os seus switches caem antes ou depois desse limite de 32 caracteres. A maioria dos switches não se importa se são processados ​​de forma redundante, mas obter um ”  ” em vez de um switch completo pode fazer com que o Perl tente executar a entrada padrão em vez do seu programa. E uma opção -I parcial também pode causar resultados ímpares.

Some switches do care if they are processed twice, for instance combinations of -l and -0. Either put all the switches after the 32-character boundary (if applicable), or replace the use of -0digits by BEGIN{ $/ = “\0digits“; }.

Parsing of the #! switches starts wherever “perl” is mentioned in the line. The sequences “-*” and “ ” are specifically ignored.

If the #! line does not contain the word “perl” nor the word “indir” the program named after the #! is executed instead of the Perl interpreter. This is slightly bizarre, but it helps people on machines that don’t do #!, because they can tell a program that their SHELL environment variable is /usr/bin/perl, and Perl will then dispatch the program to the correct interpreter for them.

After locating your program, Perl compiles the entire program to an internal form. If there are any compilation errors, execution of the program is not attempted. (This is unlike the typical shell script, which might run part-way through before finding a syntax error.)

If the program is syntactically correct, it is executed. If the program runs off the end without hitting an exit() or die() operator, an implicit exit(0) is provided to indicate successful completion.

Location Of Perl

Perl can be located wherever you choose, but it’s best for both /usr/bin/perl and /usr/local/bin/perl to be symlinks to the actual binary. If that can’t be done, system administrators are strongly encouraged to put symlinks to perl and its accompanying utilities into a directory typically found along a user’s PATH, or in some other obvious and convenient place.

In this documentation, #!/usr/bin/perl on the first line of the program will stand in for whatever method works on your system. You are advised to use a specific path if you care about a specific version:

#!/usr/local/bin/perl5.14

or if you just want to be running (at least) a certain version, place a statement like this at the top of your program:

use 5.014;

Syntax

perl [ -sTtuUWX ] [ -hv ] [ -V[:configvar] ] [ -cw ] [ -d[t][:debugger] ] 
     [ -D[number/list] ] [ -pna ] [ -Fpattern ] [ -l[octal] ] 
     [ -0[octal/hexadecimal] ] [ -Idir ] [ -m[-]module ] [ -M[-]'module...' ] 
     [ -f ] [ -C [number/list] ] [ -S ] [ -x[dir] ] [ -i[extension] ] 
     [ [-e|-E] 'command' ] [ -- ] [ programfile ] [ argument ]...

Options

perl accepts the following command-line arguments:

-0[octal/hexadecimal]
specifies the input record separator ($/) as an octal or hexadecimal number. If there are no digits, the null character is the separator. Other switches may precede or follow the digits. For example, if you have a version of find which can print filenames terminated by the null character, you can say this:

find . -name '*.orig' -print0 | perl -n0e unlink

The special value 00 will cause Perl to “slurp” files in paragraph mode. Any value 0400 or above will cause Perl to slurp files whole, but by convention the value 0777 is the one normally used for this purpose.

You can also specify the separator character using hexadecimal notation: -0xHHH…, where the H are valid hexadecimal digits. Unlike the octal form, this one may be used to specify any Unicode character, even those beyond 0xFF. So if you really want a record separator of 0777, specify it as -0x1FF. (This means that you cannot use the -x option with a directory name that consists of hexadecimal digits, or else Perl will think you have specified a hex number to -0.)

-a
turns on autosplit mode when used with a -n or -p. An implicit split command to the @F array is done as the first thing inside the implicit while loop produced by the -n or -p.

perl -ane 'print pop(@F), "\n";'

is equivalent to

while (<>) {
    @F = split(' ');
    print pop(@F), "\n";
}

An alternate delimiter may be specified using -F.

-C [number/list]
O sinalizador -C controla alguns dos recursos Perl Unicode .

A partir da versão 5.8.1, o -C pode ser seguido por um número ou uma lista de letras de opção. As letras, seus valores numéricos e efeitos são os seguintes; listar as letras é igual a somar os números.

cartanúmerodescrição
Eu1Supõe-se que STDIN esteja em UTF-8
O2STDOUT estará em UTF-8
E4STDERR estará em UTF-8
S7I + O + E
Eu8UTF-8 é a camada PerlIO padrão para fluxos de entrada
o16UTF-8 é a camada PerlIO padrão para fluxos de saída
D24i + o
UMA32.os @ARGV elementos deverão ser cordas codificados em UTF-8
eu64normalmente o ” IOEioA ” é incondicional, o L os condiciona às variáveis ​​de ambiente do código de idioma ( LC_ALL , LC_TYPE e LANG , na ordem decrescente de precedência) – se as variáveis ​​indicarem UTF-8, o ” IOEioA ” selecionado estão em vigor
uma256Defina $ {^ UTF8CACHE} como -1 para executar o código de cache UTF-8 no modo de depuração .

Por exemplo, -COE e -C6 ativam o UTF-8-ness no STDOUT e no STDERR. Repetir letras é apenas redundante, não cumulativo nem alternativo.

As opções io significam que qualquer abertura subsequente () (ou operações de E / S similares ) no escopo do arquivo atual terá a camada : utf8 PerlIO implicitamente aplicada a elas, ou seja, UTF-8 é esperado de qualquer fluxo de entrada e UTF-8 é produzido para qualquer fluxo de saída. Este é apenas o padrão, com camadas explícitas em open () e com binmode () é possível manipular fluxos como de costume.

-Cpor si só (não seguido por nenhum número ou lista de opções) ou a sequência vazia “” para a variável de ambiente PERL_UNICODE , tem o mesmo efeito que -CSDL . Em outras palavras, os identificadores de E / S padrão e a camada open () padrão são processados ​​por UTF-8, mas apenas se as variáveis ​​de ambiente do código de idioma indicarem um código de idioma UTF-8. Esse comportamento segue o comportamento UTF-8 implícito (e problemático) do Perl 5.8.0. (Consulte UTF-8 não é mais o padrão nos códigos de idioma UTF-8 em perl581delta.)

Você pode usar -C0 (ou ” 0 ” para PERL_UNICODE ) para desativar explicitamente todos os recursos Unicode acima.

A variável mágica somente leitura $ {^ UNICODE}reflete o valor numérico dessa configuração. Essa variável é definida durante a inicialização do Perl e, posteriormente, é somente leitura. Se você deseja efeitos de tempo de execução, use o três-arg open () , o dois-arg binmode () e o pragma aberto .

(No Perls anterior à 5.8.1, a opção -C era uma opção apenas para Win32 que permitia o uso de APIs Win32 de “chamada de sistema ampla” com reconhecimento de Unicode. No entanto, esse recurso praticamente não foi utilizado e, portanto, a opção de linha de comando ” reciclado “.)

Nota: Desde o perl 5.10.1, se a opção -C for usada no #!linha, ele também deve ser especificado na linha de comando, pois os fluxos padrão já estão configurados neste momento na execução do interpretador perl. Você também pode usar binmode () para definir a codificação de um fluxo de E / S.

-c
faz com que o Perl verifique a sintaxe do programa e saia sem executá-lo. Na verdade, ele executará os blocos BEGIN , UNITCHECK ou CHECK e quaisquer instruções de uso: são consideradas como ocorrendo fora da execução do seu programa. Os blocos INIT e END , no entanto, serão ignorados.
-d , -dt
executa o programa no depurador Perl ( perldebug ). Se t for especificado, isso indica ao depurador que os threads serão usados ​​no código que está sendo depurado.
-d: MOD [ = bar , baz ]
 -dt: MOD [ = bar , baz ]
executa o programa sob o controle de um módulo de depuração, criação de perfil ou rastreamento instalado como Devel :: MOD . Por exemplo, -d: DProf executa o programa usando o criador de perfil Devel :: DProf . Como no sinalizador -M , as opções podem ser passadas para o pacote Devel :: MOD , onde serão recebidas e interpretadas pela rotina de importação Devel :: MOD :: . Novamente, como -M , use –d: -MOD para chamar Devel :: MOD :: unimport em vez de importar . A lista de opções separada por vírgula deve seguir um caractere ” = “. Se t é especificado, indica ao depurador que os threads serão usados ​​no código que está sendo depurado.
-Dletters
-Dnumber
sets debugging flags. To watch how it executes your program, use -Dtls. (This works only if debugging is compiled into your Perl.) Another nice value is -Dx, which lists your compiled syntax tree. And -Dr displays compiled regular expressions; the format of the output is explained in perldebguts.

As an alternative, specify a number instead of list of letters (e.g., -D14 is equivalent to -Dtls):

numberletterdescription
1pTokenizing and parsing (with v, displays parse stack)
2sStack snapshots (with v, displays all stacks)
4lContext (loop) stack processing
8tTrace execution
16oMethod and overloading resolution
32cString/numeric conversions
64PPrint profiling info, source file input state
128mMemory and SV allocation
256fFormat processing
512rRegular expression parsing and execution
1024xSyntax tree dump
2048uTainting checks
4096UUnofficial, User hacking (reserved for private, unreleased use)
8192HHash dump — usurps values()
16384XScratchpad allocation
32768DCleaning up
65536SOp slab allocation
131072TTokenizing
262144RInclude reference counts of dumped variables (eg when using -Ds)
524288Jshow s,t,P-debug (don’t Jump over) on opcodes within package DB
1048576vVerbose: use in conjunction with other flags
2097152CCopy On Write
4194304AConsistency checks on internal structures
8388608qquiet – currently only suppresses the “EXECUTING” message
16777216Mtrace smart match resolution
33554432Bdump subroutine definitions, including special blocks like BEGIN

All these flags require -DDEBUGGING when you compile the Perl executable (but see :opd in Devel::Peek or ‘debug‘ mode in re which may change this). See the INSTALL file in the Perl source distribution for how to do this. This flag is automatically set if you include -g option when Configure asks you about optimizer/debugger flags.

If you’re just trying to get a print out of each line of Perl code as it executes, the way that sh -x provides for shell scripts, you can’t use Perl’s -D switch. Instead do this:

# If you have "env" utility
env PERLDB_OPTS="NonStop=1 AutoTrace=1 frame=2" perl -dS program
# Sintaxe do shell Bourne
PERLDB_OPTS = "NonStop = 1 AutoTrace = 1 quadro = 2" programa perl -dS
# csh sintaxe
(setenv PERLDB_OPTS "NonStop = 1 AutoTrace = 1 quadro = 2"; programa perl -dS)
-e  linha de comando
pode ser usado para inserir uma linha de programa. Se -e for fornecido, o Perl não procurará um nome de arquivo na lista de argumentos. Múltiplos comandos -e podem ser dados para criar um script de várias linhas. Certifique-se de usar ponto e vírgula onde você usaria em um programa normal.
-E  linha de comando
se comporta exatamente como -e , exceto que habilita implicitamente todos os recursos opcionais (na unidade de compilação principal).
-f
Desative a execução de $ Config {sitelib} /sitecustomize.pl na inicialização.

O Perl pode ser criado para que, por padrão, tente executar o $ Config {sitelib} /sitecustomize.pl na inicialização (em um bloco BEGIN ). Esse é um gancho que permite ao administrador do sistema personalizar como o Perl se comporta. Por exemplo, ele pode ser usado para adicionar entradas ao array @INC para fazer com que o Perl encontre módulos em locais fora do padrão.

Perl realmente insere o seguinte código:

INÍCIO {
    faça {local $ !; -f "$ Config {sitelib} /sitecustomize.pl"; }
    && do "$ Config {sitelib} /sitecustomize.pl";
}

Uma vez que é um verdadeiro fazer (e não uma exigem ), sitecustomize.pl não precisa retornar um verdadeiro valor. O código é executado no pacote principal , em seu próprio escopo lexical. No entanto, se o script morrer, $ @ não será definido.

O valor de $ Config {sitelib} também é determinado no código C e não é lido no Config.pm , que não é carregado.

O código é executado muito cedo. Por exemplo, quaisquer alterações feitas no @INC aparecerão na saída de ” perl -V “. Obviamente, os blocos END também serão executados muito tarde.

Para determinar em tempo de execução se esse recurso foi compilado em seu perl , você pode verificar o valor de $ Config {usesitecustomize} .

-F padrão
especifica o padrão para dividir se -a também estiver em vigor. O padrão pode estar entre // , “” ou  , caso contrário, será colocado entre aspas simples. Você não pode usar espaço em branco literal no padrão.
-h
imprime um resumo das opções.
-i [ extensão ]
especifica que os arquivos processados ​​pela construção <> devem ser editados no local. Isso é feito renomeando o arquivo de entrada, abrindo o arquivo de saída com o nome original e selecionando esse arquivo de saída como o padrão para instruções print () . A extensão, se fornecida, é usada para modificar o nome do arquivo antigo para fazer uma cópia de backup, seguindo estas regras:

Se nenhuma extensão for fornecida e o sistema o suportar, o arquivo original será mantido aberto sem um nome enquanto a saída é redirecionado para um novo arquivo com o nome do arquivo original. Quando o perl sai, limpa ou não, o arquivo original é desvinculado.

Se a extensão não contiver um * , ela será anexada ao final do nome do arquivo atual como sufixo. Se a extensão contiver um ou mais * caracteres, cada * será substituído pelo nome do arquivo atual. Em termos de Perl, você pode pensar nisso como:

($ backup = $ extensão) = ~ s / \ * / $ nome_do_arquivo / g;

Isso permite adicionar um prefixo ao arquivo de backup, em vez de (ou além de) um sufixo:

Perl -pi'orig_ * '-e' / bar / baz / 'fileA 
# backup em 'orig_fileA'

Ou até para colocar cópias de backup dos arquivos originais em outro diretório (desde que o diretório já exista):

Perl -pi'old / *. orig '-e' s / bar / baz / 'fileA  
# backup para 'old / fileA.orig'

Esses conjuntos de one-liners são equivalentes:

# sobrescrever arquivo atual
arquivo perl -pi -e / bar / baz / ' 
# sobrescrever arquivo atual
Perl -pi '*' -e 's / bar / baz /' fileA 
# backup em 'fileA.orig'
Perl -pi'.orig '-e' / bar / baz / 'fileA 
# backup em 'fileA.orig'
Perl -pi '*. orig' -e 's / bar / baz /' fileA 

Da casca , dizendo

perl -p -i.orig -e "s / foo / bar /; ..."

é o mesmo que usar o programa:

#! / usr / bin / perl -pi.orig s / foo / bar /;

que é equivalente a

#! / usr / bin / perl
$ extension = '.orig';
LINHA: while (<>) 
{
  if ($ ARGV ne $ oldargv) 
  {
    if ($ extensão! ~ / \ * /) 
    {
      $ backup = $ ARGV. extensão $;
    }
    outro 
    {
      ($ backup = $ extensão) = ~ s / \ * / $ ARGV / g;
    }
    renomear ($ ARGV, $ backup);
    aberto (ARGVOUT, "> $ ARGV");
    selecione (ARGVOUT);
    $ oldargv = $ ARGV;
  }
  s / foo / bar /;
}
continuar 
{
  impressão; # isso imprime no nome do arquivo original
}
selecione (STDOUT);

exceto que o formulário -i não precisa comparar $ ARGV com $ oldargv para saber quando o nome do arquivo foi alterado. No entanto, ele usa ARGVOUT para o identificador de arquivo selecionado. Observe que STDOUT é restaurado como o identificador de arquivo de saída padrão após o loop.

Como mostrado acima, o Perl cria o arquivo de backup, independentemente de qualquer saída ser realmente alterada. Portanto, esta é apenas uma maneira elegante de copiar arquivos:

Perl -p -i '/ some / file / path / *' -e 1 arquivo1 arquivo2 arquivo3 ...

ou

Perl -p -i'.orig '-e 1 arquivo1 arquivo2 arquivo3 ...

Você pode usar eof sem parênteses para localizar o final de cada arquivo de entrada, caso deseje anexar a cada arquivo ou redefinir a numeração das linhas.

Se, para um determinado arquivo, o Perl não conseguir criar o arquivo de backup conforme especificado na extensão, ele ignorará esse arquivo e continuará com o próximo (se existir).

Você não pode usar -i para criar diretórios ou remover extensões de arquivos.

O Perl não expande ~ nos nomes de arquivos, o que é bom, já que algumas pessoas o usam para seus arquivos de backup:

Perl -pi ~ -e 's / foo / bar /' arquivo1 arquivo2 arquivo3 ...

Observe que, como -i renomeia ou exclui o arquivo original antes de criar um novo arquivo com o mesmo nome, os links físicos e físicos no estilo Unix não serão preservados. Finalmente, a opção -i não impede a execução quando nenhum arquivo é fornecido na linha de comando. Nesse caso, nenhum backup é feito (o arquivo original não pode, é claro, ser determinado) e o processamento prossegue de STDIN para STDOUT conforme o esperado.

 

-I diretório
Os diretórios especificados por -I são anexados ao caminho de pesquisa de módulos ( @INC ).
-l [ octnum ]
enables automatic line-ending processing. It has two separate effects. First, it automatically chomp$/ (the input record separator) when used with -n or -p. Second, it assigns $\ (the output record separator) to have the value of octnum so that any print statements will have that separator added back on. If octnum is omitted, sets $\ to the current value of $/. For instance, to trim lines to 80 columns:

perl -lpe 'substr($_, 80) = ""'

Note that the assignment $\ = $/ is done when the switch is processed, so the input record separator can be different than the output record separator if the -l switch is followed by a -0 switch:

gnufind / -print0 | perl -ln0e 'print "found $_" if -p'

This sets $\ to newline and then sets $/ to the null character.

-m[-]module
-M[-]module
-M[-]'module ...' 
-[mM][-]module=arg[,arg]...
-mmodule executes use module(); before executing your program.

-Mmodule executes use module ; before executing your program. You can use quotes to add extra code after the module name, e.g., ‘-MMODULE qw(foo bar)’.

If the first character after the -M or -m is a dash () then the ‘use‘ is replaced with ‘no‘.

You can also say -mMODULE=foo,bar or -MMODULE=foo,bar as a shortcut for ‘-MMODULE qw(foo bar)’. This avoids the need to use quotes when importing symbols. The actual code generated by -MMODULE=foo,bar is use module split(/,/,q{foo,bar}). Note that the = form removes the distinction between -m and -M.

A consequence of this is that -MMODULE=number never does a version check, unless MODULE::import() itself is set up to do a version check, which could happen for example if MODULE inherits from Exporter.

-n
causes Perl to assume the following loop around your program, which makes it iterate over filename arguments somewhat like sed -n or awk:

LINE:
    while (<>) {
    ...           # your program goes here
}

Note that the lines are not printed by default. See -p to have lines printed. If a file named by an argument cannot be opened for some reason, Perl warns you about it and moves on to the next file.

Also, note that <> passes command line arguments to open, which doesn’t necessarily interpret them as file names.

Here is an efficient way to delete all files that haven’t been modified for at least a week:

find . -mtime +7 -print | perl -nle unlink

This is faster than using the -exec switch of find because you don’t have to start a process on every filename found. It does suffer from the bug of mishandling newlines in pathnames, which you can fix if you follow the example under -0.

BEGIN and END blocks may be used to capture control before or after the implicit program loop, just as in awk.

-p
causes Perl to assume the following loop around your program, which makes it iterate over filename arguments somewhat like sed:

LINE:
    while (<>) {
	...         # your program goes here
    } continue {
	print or die "-p destination: $!\n";
}

If a file named by an argument cannot be opened for some reason, Perl warns you about it, and moves on to the next file. Note that the lines are printed automatically. An error occurring during printing is treated as fatal. To suppress printing use the -n switch. A -p overrides a -n switch.

BEGIN and END blocks may be used to capture control before or after the implicit loop, just as in awk.

-s
enables rudimentary switch parsing for switches on the command line after the program name but before any filename arguments (or before an argument of ““). Any switch found there is removed from @ARGV and sets the corresponding variable in the Perl program. The following program prints “1” if the program is invoked with a -xyz switch, and “abc” if it is invoked with -xyz=abc.

#!/usr/bin/perl -s
if ($xyz) { print "$xyz\n" }

Do note that a switch like –help creates the variable ${-help}, which is not compliant with use strict “refs”. Also, when using this option on a script with warnings enabled you may get a lot of spurious “used only once” warnings.

-S
makes Perl use the PATH environment variable to search for the program unless the name of the program contains path separators.

On some platforms, this also makes Perl append suffixes to the filename while searching for it. For example, on Win32 platforms, the “.bat” and “.cmd” suffixes are appended if a lookup for the original name fails, and if the name does not already end in one of those suffixes. If your Perl was compiled with DEBUGGING turned on, using the -Dp switch to Perl shows how the search progresses.

Typically this is used to emulate #! startup on platforms that don’t support #!. It’s also convenient when debugging a script that uses #!, and is thus normally found by the shell’s $PATH search mechanism.

This example works on many platforms that have a shell compatible with Bourne shell:

#!/usr/bin/perl
eval 'exec /usr/bin/perl -wS $0 ${1+"$@"}'
if $running_under_some_shell;

The system ignores the first line and feeds the program to /bin/sh, which proceeds to try to execute the Perl program as a shell script. The shell executes the second line as a normal shell command, and thus starts up the Perl interpreter. On some systems $0 doesn’t always contain the full pathname, so the -S tells Perl to search for the program if necessary. After Perl locates the program, it parses the lines and ignores them because the variable $running_under_some_shell is never true. If the program will be interpreted by csh, you will need to replace ${1+”$@”} with $*, even though that doesn’t understand embedded spaces (and such) in the argument list. To start up sh rather than csh, some systems may have to replace the #! line with a line containing just a colon, which will be politely ignored by Perl. Other systems can’t control that, and need a totally devious construct that will work under any of cshsh, or perl, such as the following:

eval '(exit $?0)' && eval 'exec perl -wS $0 ${1+"$@"}'
& eval 'exec /usr/bin/perl -wS $0 $argv:q'
if $running_under_some_shell;

If the filename supplied contains directory separators (and so is an absolute or relative pathname), and if that file is not found, platforms that append file extensions will do so and try to look for the file with those extensions added, one by one.

On DOS-like platforms, if the program does not contain directory separators, it will first be searched for in the current directory before being searched for on the PATH. On Unix platforms, the program will be searched for strictly on the PATH.

-t
Like -T, but taint checks will issue warnings rather than fatal errors. These warnings can now be controlled normally with no warnings qw(taint).

Note: This is not a substitute for -T! This is meant to be used only as a temporary development aid while securing legacy code: for real production code and for new secure code written from scratch, always use the real -T.

-T
turns on “taint” so you can test them. Ordinarily these checks are done only when running setuid or setgid. It’s a good idea to turn them on explicitly for programs that run on behalf of someone else whom you might not necessarily trust, such as CGI programs or any Internet servers you might write in Perl. For security reasons, this option must be seen by Perl quite early; usually this means it must appear early on the command line or in the #! line for systems which support that construct.
-u
This switch causes Perl to dump core after compiling your program. You can then in theory take this core dump and turn it into an executable file by using the undump program. This speeds startup at the expense of some disk space (which you can minimize by stripping the executable). If you want to execute a portion of your program before dumping, use the dump() operator instead. Note: availability of undump is platform specific.
-U
allows Perl to do unsafe operations. Currently the only “unsafe” operations are attempting to unlink directories while running as superuser and running setuid programs with fatal taint checks turned into warnings. Note that warnings must be enabled along with this option to actually generate the taint-check warnings.
-v
prints the version and patchlevel of your perl executable.
-V
prints summary of the major perl configuration values and the current values of @INC.
-V:configvar
Prints to STDOUT the value of the named configuration variable(s), with multiples when your configvar argument looks like a regex (has non-letters). For example:

perl -V:libc
libc='/lib/libc-2.2.4.so';
perl -V:lib.
libs='-lnsl -lgdbm -ldb -ldl -lm -lcrypt -lutil -lc';
libc='/lib/libc-2.2.4.so';
perl -V:lib.*
libpth='/usr/local/lib /lib /usr/lib';
libs='-lnsl -lgdbm -ldb -ldl -lm -lcrypt -lutil -lc';
lib_ext='.a';
libc='/lib/libc-2.2.4.so';
libperl='libperl.a';
....

Additionally, extra colons can be used to control formatting. A trailing colon suppresses the linefeed and terminator “;“, allowing you to embed queries into shell commands. (mnemonic: PATH separator “:“.)

echo "compression-vars: " `perl -V:z.*: ` " are here !" 
compression-vars: zcat='' zip='zip' are here !

A leading colon removes the “name=” part of the response, this allows you to map to the name you need. (mnemonic: empty label)

echo "goodvfork="`./perl -Ilib -V::usevfork`
goodvfork=false;

Leading and trailing colons can be used together if you need positional parameter values without the names. Note that in the case below, the PERL_API parameters are returned in alphabetical order.

echo building_on `perl -V::osname: -V::PERL_API_.*:` now 
building_on 'linux' '5' '1' '9' now
-w
imprime avisos sobre construções duvidosas, como nomes de variáveis ​​mencionados apenas uma vez e variáveis ​​escalares usadas antes de serem definidas; sub-rotinas redefinidas; referências a identificadores de arquivo indefinidos; identificadores de arquivo abertos somente leitura nos quais você está tentando gravar; valores usados ​​como um número que não se parece com números; usando uma matriz como se fosse um escalar; se suas sub-rotinas recuarem mais de 100 profundas; e inúmeras outras coisas.

Essa opção realmente apenas habilita a variável global $ ^ W ; normalmente, o pragma de advertência de uso de escopo lexicamente é o preferido. Você pode desativar ou promover erros fatais avisos específicos usando ganchos __WARN__ , conforme descrito em perlvar e warn . Veja também perldiag eperltrap . Um recurso de aviso refinado também está disponível se você deseja manipular classes inteiras de avisos.

-W
Permite que todos os avisos, independentemente de qualquer aviso ou $ ^ W .
-X
Desativa todos os avisos, independentemente de avisos de uso ou $ ^ W .

Diretório -x -x
informa ao Perl que o programa está incorporado em um pedaço maior de texto não relacionado, como em uma mensagem de correio. O lixo principal será descartado até a primeira linha que começa com #! e contém a string ” perl “. Quaisquer opções significativas nessa linha serão aplicadas.

Todas as referências aos números de linha pelo programa (avisos, erros, …) tratam o #! linha como a primeira linha. Portanto, um aviso na segunda linha do programa, que está na 100ª linha do arquivo, será relatado como linha 2, não como linha 100. Isso pode ser substituído usando a diretiva #line .

Se um nome de diretório for especificado, o Perl mudará para esse diretório antes de executar o programa. O -xswitch controla apenas o descarte do lixo principal. O programa deve ser finalizado com __END__ se houver lixo à direita a ser ignorado; o programa pode processar todo ou qualquer lixo posterior por meio do identificador de arquivo DATA, se desejado.

O diretório, se especificado, deve aparecer imediatamente após o -x, sem espaço em branco.

Meio Ambiente

As seguintes variáveis ​​de ambiente afetam a operação do perl :

CASA
Usado se chdir não tem argumento.
LOGDIR
Usado se chdir não tem argumento e HOME não está definido.
CAMINHO
Usado na execução de subprocessos e na localização do programa se -S for usado.
PERL5LIB
Uma lista de diretórios nos quais procurar arquivos de biblioteca Perl antes de procurar na biblioteca padrão e no diretório atual. Todos os diretórios específicos da arquitetura e da versão, como version / archname / , version / ou archname / nos locais especificados, serão incluídos automaticamente, se existirem, com essa pesquisa feita no momento da inicialização do intérprete. Além disso, quaisquer diretórios correspondentes às entradas em $ Config {inc_version_list} são adicionados. (Normalmente, isso seria para versões perl compatíveis mais antigas instaladas na mesma árvore de diretórios.)

Se PERL5LIB não estiver definido, PERLLIB será usado. Diretórios são separados (como em PATH) por dois pontos em plataformas semelhantes ao Unix e por ponto e vírgula no Windows (o separador de caminho apropriado é fornecido pelo comando perl -V: path_sep ).

Ao executar verificações de contaminação, porque o programa estava executando setuid ou setgid ou a opção -T ou -t foi especificada, nem PERL5LIB nem PERLLIB são consultados. O programa deveria dizer:

use lib "/ my / directory";
PERL5OPT
Opções de linha de comando (comutadores). Os comutadores nessa variável são tratados como se estivessem em todas as linhas de comando do Perl. Somente as opções  [ CDIMUdmtwW ] são permitidas. Ao executar verificações de contaminação (porque o programa estava executando setuid ou setgid ou porque a opção -T ou -t foi usada), essa variável é ignorada. Se o PERL5OPT começar com -T , a contaminação será ativada e as opções subsequentes ignoradas. Se o PERL5OPT começar com -t , a contaminação será ativada, um ponto gravável removido do @INC e as opções subsequentes serão respeitadas.
PERLIO
Uma lista separada por espaços (ou dois pontos) de camadas do PerlIO. Se o perl for criado para usar o sistema PerlIO para E / S (o padrão), essas camadas afetarão as E / S do Perl.

É convencional iniciar nomes de camadas com dois pontos (por exemplo : perlio ) para enfatizar sua semelhança com os “atributos” variáveis. Mas o código que analisa as strings de especificação de camada, que também é usado para decodificar a variável de ambiente PERLIO , trata os dois pontos como um separador.

Um PERLIO não definido ou vazio é equivalente ao conjunto de camadas padrão para sua plataforma; por exemplo ,: unix: perlio em sistemas semelhantes ao Unix e : unix: crlf no Windows e outros sistemas semelhantes ao DOS .

A lista se torna o padrão para todas as E / S do Perl. Consequentemente, apenas as camadas internas podem aparecer nesta lista, pois as camadas externas (como : encoding () ) precisam de E / S para carregá-las. Consulte pragma aberto para saber como adicionar codificações externas como padrões.

As camadas que fazem sentido incluir na variável de ambiente PERLIO são resumidas resumidamente abaixo. Para mais detalhes, consulte PerlIO .

: bytesUma pseudo camada que desativa o sinalizador : utf8 para a camada abaixo; provavelmente não será útil por si só na variável de ambiente global PERLIO . Você talvez estivesse pensando em : crlf: bytes ou : perlio: bytes .
: crlfA layer which does CRLF to “\n” translation distinguishing “text” and “binary” files in the manner of MS-DOS and similar operating systems. (It currently does not mimic MS-DOS as far as treating of Control-Z as being an end-of-file marker.)
:mmapA layer that implements “reading” of files by using mmap to make an entire file appear in the process’s address space, and then using that as PerlIO’s “buffer”.
:perlioThis is a re-implementation of stdio-like buffering written as a PerlIO layer. As such it will call whatever layer is below it for its operations, typically :unix.
:popAn experimental pseudo layer that removes the topmost layer. Use with the same care as is reserved for nitroglycerin.
:rawA pseudo layer that manipulates other layers. Applying the :raw layer is equivalent to calling binmode($fh). It makes the stream pass each byte as-is without translation. In particular, both CRLF translation and intuiting :utf8 from the locale are disabled.

Unlike in earlier versions of Perl, :raw is not just the inverse of :crlf : other layers which would affect the binary nature of the stream are also removed or disabled.

:stdioThis layer provides a PerlIO interface by wrapping system’s ANSI C “stdio” library calls. The layer provides both buffering and IO. Note that the :stdio layer does not do CRLF translation even if that is the platform’s normal behaviour. You will need a :crlf layer above it to do that.
:unixLow-level layer that calls readwritelseek, etc.
:utf8A pseudo layer that enables a flag in the layer below to tell Perl that output should be in utf8 and that input should be regarded as already in valid utf8 form. WARNING: It does not check for validity and as such should be handled with extreme caution for input, because security violations can occur with non-shortest UTF-8 encodings, etc. Generally :encoding(utf8) is the best option when reading UTF-8 encoded data.
:win32On Win32 platforms this experimental layer uses native “handle” IO rather than a Unix-like numeric file descriptor layer. Known to be buggy in release 5.14.

O conjunto padrão de camadas deve fornecer resultados aceitáveis ​​em todas as plataformas.

Para plataformas Unix, isso será equivalente a ” unix perlio ” ou ” stdio “. O Configure está configurado para preferir a implementação ” stdio ” se a biblioteca do sistema fornecer acesso rápido ao buffer; caso contrário, ele usa a implementação ” unix perlio “.

No Win32, o padrão nesta versão (5.14) é ” unix crlf “. O ” stdio ” do Win32 possui vários bugs / recursos incorretos para o Perl IO, dependendo da versão e do fornecedor do compilador C. Usar nossa própria camada crlf como buffer evita esses problemas e torna as coisas mais uniformes. A camada crlf fornece conversão CRLF, bem como buffer.

A versão atual (5.14 até a presente redação) usa o unix como a camada inferior no Win32 e, portanto, ainda usa as rotinas de descrição de arquivos numéricos do compilador C. Há uma camada win32 nativa experimental, que deve ser aprimorada e deve se tornar o padrão no Win32.

A variável de ambiente PERLIO é completamente ignorada quando o Perl é executado no modo de contaminação.

PERLIO_DEBUG
Se definido como o nome de um arquivo ou dispositivo, certas operações do subsistema PerlIO serão registradas nesse arquivo, que é aberto no modo de acréscimo. Os usos típicos estão no Unix:

env PERLIO_DEBUG = / dev / tty script perl ...

e no Win32, o equivalente aproximadamente:

set PERLIO_DEBUG=CON
perl script ...

This functionality is disabled for setuid scripts and for scripts run with -T.

PERLLIB
A list of directories in which to look for Perl library files before looking in the standard library and the current directory. If PERL5LIB is defined, PERLLIB is not used.

The PERLLIB environment variable is completely ignored when Perl is run in taint mode.

PERL5DB
The command used to load the debugger code. The default is:

BEGIN { require "perl5db.pl" }

The PERL5DB environment variable is only used when Perl is started with a bare -d switch.

PERL5DB_THREADED
If set to a true value, indicates to the debugger that the code being debugged uses threads.
PERL5SHELL
(specific to the Win32 port.) On Win32 ports only, may be set to an alternative shell that Perl must use internally for executing “backtick” commands or system(). Default is cmd.exe /x/d/c on Windows NT and command.com /c on Windows95. The value is considered space-separated. Precede any character that needs to be protected, like a space or backslash, with another backslash.

Note that Perl doesn’t use COMSPEC for this purpose because COMSPEC has a high degree of variability among users, leading to portability concerns. Besides, Perl can use a shell that may not be fit for interactive use, and setting COMSPEC to such a shell may interfere with the proper functioning of other programs (which usually look in COMSPEC to find a shell fit for interactive use).

Before Perl 5.10.0 and 5.8.8, PERL5SHELL was not taint checked when running external commands. It is recommended that you explicitly set (or delete) $ENV{PERL5SHELL} when running in taint mode under Windows.

PERL_ALLOW_NON_IFS_LSP
(specific to the Win32 port.) Set to 1 to allow the use of non-IFS compatible LSPs (Layered Service Providers). Perl normally searches for an IFS-compatible LSP because this is required for its emulation of Windows sockets as real file handles. However, this may cause problems if you have a firewall such as McAfee Guardian, which requires that all applications use its LSP but that is not IFS-compatible, because clearly Perl will normally avoid using such an LSP.

Setting this environment variable to 1 means that Perl will use the first suitable LSP enumerated in the catalog, which keeps McAfee Guardian happy, and in that particular case Perl still works too because McAfee Guardian’s LSP actually plays other games which allow applications requiring IFS compatibility to work.

PERL_DEBUG_MSTATS
Relevant only if Perl is compiled with the malloc included with the Perl distribution; that is, if perl -V:d_mymalloc is “define“.

If set, this dumps out memory statistics after execution. If set to an integer greater than one, also dumps out memory statistics after compilation.

PERL_DESTRUCT_LEVEL
Relevant only if your Perl executable was built with -DDEBUGGING, this controls the behaviour of global destruction of objects and other references.
PERL_DL_NONLAZY
Set to “1” to have Perl resolve all undefined symbols when it loads a dynamic library. The default behaviour is to resolve symbols when they are used. Setting this variable is useful during testing of extensions, as it ensures that you get an error on misspelled function names even if the test suite doesn’t call them.
PERL_ENCODING
If using the use encoding pragma without an explicit encoding name, the PERL_ENCODING environment variable is consulted for an encoding name.
PERL_HASH_SEED
(Since Perl 5.8.1, new semantics in Perl 5.18.0) Used to override the randomization of Perl’s internal hash function. The value is expressed in hexadecimal, and may include a leading 0x. Truncated patterns are treated as though they are suffixed with sufficient 0‘s as required.

If the option is provided, and PERL_PERTURB_KEYS is NOT set, then a value of ‘0‘ implies PERL_PERTURB_KEYS=0 and any other value implies PERL_PERTURB_KEYS=2.

PLEASE NOTE: The hash seed is sensitive information. Hashes are randomized to protect against local and remote attacks against Perl code. By manually setting a seed, this protection may be partially or completely lost.

PERL_PERTURB_KEYS
(Since Perl 5.18.0) Set to “0” or “NO” then traversing keys will be repeatable from run to run for the same PERL_HASH_SEED. Insertion into a hash will not change the order, except to provide for more space in the hash. When combined with setting PERL_HASH_SEED this mode is as close to pre 5.18 behavior as you can get.

When set to “1” or “RANDOM” then traversing keys will be randomized. Every time a hash is inserted into the key order will change in a random fashion. The order may not be repeatable in a following program run even if the PERL_HASH_SEED has been specified. This is the default mode for perl.

When set to “2” or “DETERMINISTIC” then inserting keys into a hash will cause the key order to change, but in a way that is repeatable from program run to program run.

NOTE: Use of this option is considered insecure, and is intended only for debugging non-deterministic behavior in Perl’s hash function. Do not use it in production.

PERL_HASH_SEED_DEBUG
(Since Perl 5.8.1.) Set to “1” to display (to STDERR) information about the hash function, seed, and what type of key traversal randomization is in effect at the beginning of execution. This, combined with PERL_HASH_SEED and PERL_PERTURB_KEYS is intended to aid in debugging nondeterministic behaviour caused by hash randomization.

Note that any information about the hash function, especially the hash seed is sensitive information: by knowing it, one can craft a denial-of-service attack against Perl code, even remotely. Do not disclose the hash seed to people who don’t need to know it. See also hash_seed() and key_traversal_mask() in Hash::Util.

An example output might be:

HASH_FUNCTION = ONE_AT_A_TIME_HARD HASH_SEED = 
0x652e9b9349a7a032 PERTURB_KEYS = 1 (RANDOM)
PERL_MEM_LOG
If your Perl was configured with -Accflags=-DPERL_MEM_LOG, setting the environment variable PERL_MEM_LOG enables logging debug messages. The value has the form <number>[m][s][t], where number is the file descriptor number you want to write to (2 is default), and the combination of letters specifies that you want information about (m)emory and/or (s)v, optionally with (t)imestamps. For example, PERL_MEM_LOG=1mst logs all information to stdout. You can write to other opened file descriptors in a variety of ways:

$ 3>foo3 PERL_MEM_LOG=3m perl ...
PERL_ROOT
(specific to the VMS port.) A translation-concealed rooted logical name that contains Perl and the logical device for the @INC path on VMS only. Other logical names that affect Perl on VMS include PERLSHRPERL_ENV_TABLES, and SYS$TIMEZONE_DIFFERENTIAL, but are optional and discussed further in perlvms and in README.vms in the Perl source distribution.
PERL_SIGNALS
Available in Perls 5.8.1 and later. If set to “unsafe“, the pre-Perl-5.8.0 signal behaviour (which is immediate but unsafe) is restored. If set to safe, then safe (but deferred) signals are used.
PERL_UNICODE
Equivalent to the -C command-line switch. Note that this is not a boolean variable. Setting this to “1” is not the right way to “enable Unicode”. You can use “0” to “disable Unicode”, though (or alternatively unset PERL_UNICODE in your shell before starting Perl). See the description of the -C switch for more information.
SYS$LOGIN
(específico da porta VMS.) Usado se chdir não tiver argumento e HOME e LOGDIR não estiverem configurados.

O Perl e seus vários módulos e componentes, incluindo suas estruturas de teste, às vezes podem fazer uso de outras variáveis ​​de ambiente. Alguns deles são específicos para uma plataforma específica. Consulte a documentação apropriada do módulo e qualquer documentação para sua plataforma para variáveis ​​peculiares a essas situações específicas.

O Perl disponibiliza todas as variáveis ​​de ambiente para o programa que está sendo executado e as repassa para qualquer processo filho iniciado. No entanto, os programas que executam setuid fariam bem em executar as seguintes linhas antes de fazer qualquer outra coisa, apenas para manter as pessoas honestas:

$ ENV {CAMINHO} = "/ bin: / usr / bin"; # ou o que você precisar
$ ENV {SHELL} = "/ bin / sh" se existir $ ENV {SHELL};
excluir @ENV {qw (IFS CDPATH ENV BASH_ENV)};

Veja também:

Sintaxe
Tipos de dados
Perl Sub-rotinas
Perl Operadores
Perl Funções
Perl Pragmas Perl

awk – Intérprete para a linguagem de programação de processamento de texto AWK.
sed – Um utilitário para filtrar e transformar texto.

21 de novembro de 2019

Sobre nós

A Linux Force Brasil é uma empresa que ama a arte de ensinar. Nossa missão é criar talentos para a área de tecnologia e atender com excelência nossos clientes.

CNPJ: 13.299.207/0001-50
SAC:         0800 721 7901

[email protected]

Comercial  Comercial: (11) 3796-5900

Suporte:    (11) 3796-5900
[email protected]

Copyright © Linux Force Security  - Desde 2011.