# Referência Rápida de Perl

*Variáveis, regex, E/S de arquivos, referências, módulos essenciais*

> Source: Perl Documentation (perldoc.perl.org) · MIT

## 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

| Command | Description |
|---------|-------------|
| `$scalar` | Valor único (string, número, referência) |
| `@array` | Lista ordenada de escalares |
| `%hash` | Pares 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

| Command | Description |
|---------|-------------|
| `$_` | Variável padrão (tópico) |
| `@_` | Argumentos de sub-rotina |
| `$!` | Mensagem de erro do sistema |
| `$@` | Erro de eval |
| `$0` | Nome do programa |
| `@ARGV` | Argumentos da linha de comando |
| `%ENV` | Variáveis de ambiente |

## Operadores

### Operadores de Comparação

| Command | Description |
|---------|-------------|
| `==, !=, <, >, <=, >=` | Comparação numérica |
| `eq, ne, lt, gt, le, ge` | Comparação de strings |
| `<=>` | Spaceship numérico (retorna -1, 0, 1) |
| `cmp` | Spaceship 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

| Command | Description |
|---------|-------------|
| `&& / and` | AND lógico (baixa precedência: `and`) |
| `\|\| / or` | OR lógico (baixa precedência: `or`) |
| `// ` | Defined-or (retorna esquerda se definido) |
| `! / not` | NOT 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 = <STDIN>) { chomp $line; }
until ($done) { last if check(); }
```

### Controle de Laço

| Command | Description |
|---------|-------------|
| `next` | Pular para próxima iteração (como `continue`) |
| `last` | Sair do laço (como `break`) |
| `redo` | Reiniciar iteração atual |
| `next LABEL` | Pular para próxima iteração do laço rotulado |
| `last LABEL` | Sair 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

| Command | Description |
|---------|-------------|
| `/i` | Insensível a maiúsculas |
| `/g` | Global (todas as correspondências) |
| `/m` | Multilinha (`^` e `$` correspondem a limites de linha) |
| `/s` | Linha única (`.` corresponde a nova linha) |
| `/x` | Estendido (permite espaços em branco e comentários) |

### Padrões Comuns

| Command | Description |
|---------|-------------|
| `\d, \D` | Dígito / não dígito |
| `\w, \W` | Caractere de palavra / não palavra |
| `\s, \S` | Espaço em branco / não espaço |
| `\b` | Limite 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

| Command | Description |
|---------|-------------|
| `-e $path` | Arquivo existe |
| `-f $path` | É um arquivo regular |
| `-d $path` | É um diretório |
| `-r / -w / -x` | Legível / gravável / executável |
| `-s $path` | Tamanho do arquivo em bytes (0 se vazio) |
| `-z $path` | Arquivo 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

| Command | Description |
|---------|-------------|
| `scalar @arr` | Número de elementos |
| `push / pop` | Adicionar/remover do final |
| `shift / unshift` | Remover/adicionar do início |
| `splice(@a, 2, 1)` | Remover 1 elemento no índice 2 |
| `sort @arr` | Ordenar alfabeticamente |
| `reverse @arr` | Inverter ordem |
| `grep { /pat/ } @arr` | Filtrar por padrão |
| `map { $_ * 2 } @arr` | Transformar 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()

| Command | Description |
|---------|-------------|
| `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

| Command | Description |
|---------|-------------|
| `List::Util` | sum, max, min, reduce, any, all |
| `File::Basename` | basename, dirname, fileparse |
| `File::Path` | make_path, remove_tree |
| `Getopt::Long` | Análise de opções da linha de comando |
| `JSON` | encode_json, decode_json |
| `LWP::Simple` | get($url) — cliente HTTP simples |
| `Data::Dumper` | Dump de depuração de estruturas de dados |
| `Carp` | croak, confess — melhores mensagens de erro |

### CPAN

```
cpan install Module::Name        # install from CPAN
cpanm Module::Name               # cpanminus (faster)
perldoc Module::Name             # read module docs
```
