Básico
Hello World
#!/usr/bin/perl use strict; use warnings; print "Hello, World!\n"; say "Hello, World!"; # with use feature 'say';
Executar Perl
perl script.pl # run a file perl -e 'print "hi\n"' # run inline perl -ne 'print' file # process file line by line
Comentários e Documentação
# single-line comment =pod Multi-line POD documentation =cut
Variáveis
Sigils
$scalarValor único (string, número, referência)
@arrayLista ordenada de escalares
%hashPares chave-valor
$array[0]Acessar elemento único de array (contexto escalar)
$hash{key}Acessar valor único de hash (contexto escalar)
Variáveis Escalares
my $name = "Perl"; # string my $version = 5.40; # number my $count = 42; # integer my $undef; # undefined (undef) my $combined = "$name v$version"; # interpolation
Contexto
my @arr = (1, 2, 3); my $count = @arr; # scalar context: 3 my @copy = @arr; # list context: (1, 2, 3) my $len = scalar @arr; # force scalar context
Variáveis Especiais
$_Variável padrão (tópico)
@_Argumentos de sub-rotina
$!Mensagem de erro do sistema
$@Erro de eval
$0Nome do programa
@ARGVArgumentos da linha de comando
%ENVVariáveis de ambiente
Operadores
Operadores de Comparação
==, !=, <, >, <=, >=Comparação numérica
eq, ne, lt, gt, le, geComparação de strings
<=>Spaceship numérico (retorna -1, 0, 1)
cmpSpaceship de strings
=~Correspondência / ligação com regex
!~Correspondência negada com regex
Operadores de String
my $full = "Hello" . " " . "World"; # concatenation my $line = "-" x 40; # repetition my $len = length($full); # 11
Operadores Lógicos
&& / andAND lógico (baixa precedência: and)
|| / orOR lógico (baixa precedência: or)
// Defined-or (retorna esquerda se definido)
! / notNOT lógico
? :Ternário condicional
Controle de Fluxo
Condicionais
if ($x > 0) { print "positive\n"; } elsif ($x == 0) { print "zero\n"; } else { print "negative\n"; } print "yes\n" if $condition; # postfix if print "no\n" unless $condition; # postfix unless
Laços
for my $i (0..9) { print "$i\n"; } foreach my $item (@array) { print "$item\n"; } while ($line = ) { chomp $line; } until ($done) { last if check(); }
Controle de Laço
nextPular para próxima iteração (como continue)
lastSair do laço (como break)
redoReiniciar iteração atual
next LABELPular para próxima iteração do laço rotulado
last LABELSair do laço rotulado
Given / When
use feature 'switch'; given ($status) { when ("ok") { say "success"; } when ("error") { say "failed"; } default { say "unknown"; } }
Sub-rotinas
Sub-rotina Básica
sub greet { my ($name) = @_; return "Hello, $name!"; } my $msg = greet("Alice");
Parâmetros Padrão e Nomeados
sub connect { my (%opts) = @_; my $host = $opts{host} // "localhost"; my $port = $opts{port} // 5432; return "$host:$port"; } connect(host => "db.example.com", port => 3306);
Referências de Sub-rotinas
my $double = sub { return $_[0] * 2; }; print $double->(5); # 10 my @sorted = sort { $a <=> $b } @nums;
Protótipos e Assinaturas
use feature 'signatures'; sub add($a, $b) { return $a + $b; } sub greet($name, $greeting = "Hello") { return "$greeting, $name!"; }
Regex
Correspondência
if ($str =~ /pattern/) { print "matched\n"; } if ($str =~ /(\d+)/) { print "number: $1\n"; } my @matches = ($str =~ /(\w+)/g); # all matches
Substituição
$str =~ s/old/new/; # first occurrence $str =~ s/old/new/g; # global (all occurrences) $str =~ s/^\s+|\s+$//g; # trim whitespace (my $clean = $str) =~ s/\W//g; # non-destructive copy
Modificadores
/iInsensível a maiúsculas
/gGlobal (todas as correspondências)
/mMultilinha (^ e $ correspondem a limites de linha)
/sLinha única (. corresponde a nova linha)
/xEstendido (permite espaços em branco e comentários)
Padrões Comuns
\d, \DDígito / não dígito
\w, \WCaractere de palavra / não palavra
\s, \SEspaço em branco / não espaço
\bLimite de palavra
(?: ... )Grupo não capturante
(?<name> ... )Captura nomeada (acessar via $+{name})
E/S de Arquivos
Abrir e Ler
open(my $fh, '<', 'data.txt') or die "Cannot open: $!"; while (my $line = <$fh>) { chomp $line; print "$line\n"; } close($fh);
Escrever e Acrescentar
open(my $fh, '>', 'out.txt') or die "Cannot open: $!"; print $fh "Hello\n"; close($fh); open(my $fh, '>>', 'log.txt') or die "Cannot open: $!"; print $fh "entry\n"; close($fh);
Ler Arquivo Inteiro
use File::Slurp; my $content = read_file('data.txt'); my @lines = read_file('data.txt', chomp => 1);
Testes de Arquivo
-e $pathArquivo existe
-f $pathÉ um arquivo regular
-d $pathÉ um diretório
-r / -w / -xLegível / gravável / executável
-s $pathTamanho do arquivo em bytes (0 se vazio)
-z $pathArquivo tem tamanho zero
Arrays e Hashes
Arrays
my @arr = (1, 2, 3, 4, 5); push @arr, 6; # append my $last = pop @arr; # remove last my $first = shift @arr; # remove first unshift @arr, 0; # prepend my @slice = @arr[1..3]; # slice
Funções de Array
scalar @arrNúmero de elementos
push / popAdicionar/remover do final
shift / unshiftRemover/adicionar do início
splice(@a, 2, 1)Remover 1 elemento no índice 2
sort @arrOrdenar alfabeticamente
reverse @arrInverter ordem
grep { /pat/ } @arrFiltrar por padrão
map { $_ * 2 } @arrTransformar cada elemento
join(',', @arr)Juntar em string
Hashes
my %user = (name => "Alice", age => 30); $user{email} = "a\@b.com"; # add pair delete $user{age}; # remove pair my @keys = keys %user; my @vals = values %user;
Iteração de Hash
while (my ($k, $v) = each %hash) { print "$k => $v\n"; } for my $key (sort keys %hash) { print "$key: $hash{$key}\n"; }
Referências
Criando Referências
my $scalar_ref = \$name; my $array_ref = \@arr; my $hash_ref = \%hash; my $anon_arr = [1, 2, 3]; # anonymous array ref my $anon_hash = {a => 1, b => 2}; # anonymous hash ref
Desreferenciação
print $$scalar_ref; # dereference scalar print $array_ref->[0]; # arrow notation print $hash_ref->{key}; # arrow notation my @copy = @$array_ref; # dereference to array my %copy = %$hash_ref; # dereference to hash
Estruturas de Dados Complexas
my @users = ( { name => "Alice", age => 30 }, { name => "Bob", age => 25 }, ); print $users[0]->{name}; # "Alice"
Função ref()
ref($r) eq 'SCALAR'Referência a escalar
ref($r) eq 'ARRAY'Referência a array
ref($r) eq 'HASH'Referência a hash
ref($r) eq 'CODE'Referência a sub-rotina
Módulos
Usando Módulos
use strict; use warnings; use List::Util qw(sum max min); use File::Basename; use Cwd qw(abs_path);
Criando um Módulo
# MyModule.pm package MyModule; use Exporter 'import'; our @EXPORT_OK = qw(helper); sub helper { return "help"; } 1; # module must return true
Módulos Core Comuns
List::Utilsum, max, min, reduce, any, all
File::Basenamebasename, dirname, fileparse
File::Pathmake_path, remove_tree
Getopt::LongAnálise de opções da linha de comando
JSONencode_json, decode_json
LWP::Simpleget($url) — cliente HTTP simples
Data::DumperDump de depuração de estruturas de dados
Carpcroak, confess — melhores mensagens de erro
CPAN
cpan install Module::Name # install from CPAN cpanm Module::Name # cpanminus (faster) perldoc Module::Name # read module docs