Communitygithub.com

perl-patterns

Patrones, mejores prácticas y convenciones modernas de Perl 5.36+ para construir aplicaciones Perl robustas y mantenibles. Úsalo al escribir o revisar código Perl 5.36+ moderno.

¿Qué es perl-patterns?

Este skill proporciona un conjunto completo de patrones y mejores prácticas para el desarrollo en Perl 5.36+ moderno. Está diseñado para ayudar a desarrolladores y revisores a escribir código Perl que sea robusto, mantenible y que cumpla con los últimos estándares del lenguaje. Incluye directrices sobre el uso del pragma `v5.36`, firmas de subrutinas, sensibilidad al contexto, desreferenciación postfija y el operador `isa`. También cubre el manejo de errores con `eval/die`, Try::Tiny y el `try/catch` nativo de 5.40+, junto con programación orientada a objetos moderna utilizando Moo, Moose cuando sea necesario y la palabra clave nativa `class` de 5.38+. Además, aborda el uso de expresiones regulares con capturas nombradas y el flag `/x`, y el acceso seguro a estructuras de datos anidadas. El skill es aplicable tanto para escribir código nuevo como para refactorizar código legacy, y es compatible con todos los entornos que utilicen Perl 5.36 o superior.

Compatible con~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/perl-patterns

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Patrones Modernos de Desarrollo en Perl

Patrones idiomáticos de Perl 5.36+ y mejores prácticas para construir aplicaciones robustas y mantenibles.

Cuándo Activar

  • Escribir nuevo código o módulos Perl
  • Revisar código Perl para cumplimiento idiomático
  • Refactorizar código Perl heredado a estándares modernos
  • Diseñar la arquitectura de módulos Perl
  • Migrar código anterior a 5.36 a Perl moderno

Cómo Funciona

Aplica estos patrones como una inclinación hacia los valores predeterminados de Perl 5.36+: firmas, módulos explícitos, manejo de errores enfocado y límites comprobables. Los ejemplos a continuación están pensados para ser copiados como puntos de partida, y luego ajustados para la aplicación real, la pila de dependencias y el modelo de despliegue que tengas delante.

Principios Fundamentales

1. Utiliza el pragma v5.36

Un solo use v5.36 reemplaza el antiguo código repetitivo y habilita strict, warnings y firmas de subrutinas.

# Bien: Preámbulo moderno
use v5.36;

sub saludar($nombre) {
    say "¡Hola, $nombre!";
}

# Mal: Código repetitivo heredado
use strict;
use warnings;
use feature 'say', 'signatures';
no warnings 'experimental::signatures';

sub saludar {
    my ($nombre) = @_;
    say "¡Hola, $nombre!";
}

2. Firmas de Subrutina

Utiliza firmas para mayor claridad y verificación automática de aridad.

use v5.36;

# Bien: Firmas con valores predeterminados
sub conectar_db($host, $port = 5432, $timeout = 30) {
    # $host es obligatorio, otros tienen valores predeterminados
    return DBI->connect("dbi:Pg:host=$host;port=$port", undef, undef, {
        RaiseError => 1,
        PrintError => 0,
    });
}

# Bien: Parámetro slurpy para argumentos variables
sub mensaje_log($nivel, @detalles) {
    say "[$nivel] " . join(' ', @detalles);
}

# Mal: Desempaquetado manual de argumentos
sub conectar_db {
    my ($host, $port, $timeout) = @_;
    $port    //= 5432;
    $timeout //= 30;
    # ...
}

3. Sensibilidad al Contexto

Entiende el contexto escalar vs lista — un concepto fundamental de Perl.

use v5.36;

my @items = (1, 2, 3, 4, 5);

my @copia  = @items;            # Contexto lista: todos los elementos
my $contar = @items;            # Contexto escalar: cuenta (5)
say "Elementos: " . scalar @items; # Forzar contexto escalar

4. Desreferencia Postfija

Utiliza la sintaxis de desreferencia postfija para legibilidad con estructuras anidadas.

use v5.36;

my $datos = {
    usuarios => [
        { nombre => 'Alicia', roles => ['admin', 'usuario'] },
        { nombre => 'Roberto', roles => ['usuario'] },
    ],
};

# Bien: Desreferencia postfija
my @usuarios = $datos->{usuarios}->@*;
my @roles = $datos->{usuarios}[0]{roles}->@*;
my %primero = $datos->{usuarios}[0]->%*;

# Mal: Desreferencia circumfija (más difícil de leer en cadenas)
my @usuarios = @{ $datos->{usuarios} };
my @roles = @{ $datos->{usuarios}[0]{roles} };

5. El Operador isa (5.32+)

Comprobación de tipo infijo — reemplaza blessed($o) && $o->isa('X').

use v5.36;
if ($obj isa 'Mi::Clase') { $obj->hacer_algo }

Manejo de Errores

Patrón eval/die

use v5.36;

sub parsear_config($ruta) {
    my $contenido = eval { path($ruta)->slurp_utf8 };
    die "Error de configuración: $@" if $@;
    return decode_json($contenido);
}

Try::Tiny (Manejo Confiable de Excepciones)

use v5.36;
use Try::Tiny;

sub obtener_usuario($id) {
    my $usuario = try {
        $db->resultset('Usuario')->find($id)
            // die "Usuario $id no encontrado\n";
    }
    catch {
        warn "Falló al obtener usuario $id: $_";
        undef;
    };
    return $usuario;
}

try/catch Nativo (5.40+)

use v5.40;

sub dividir($x, $y) {
    try {
        die "División por cero" if $y == 0;
        return $x / $y;
    }
    catch ($e) {
        warn "Error: $e";
        return;
    }
}

POO Moderna con Moo

Prefiere Moo para POO moderna y ligera. Usa Moose solo cuando su metaprotocolo sea necesario.

# Bien: Clase Moo
package Usuario;
use Moo;
use Types::Standard qw(Str Int ArrayRef);
use namespace::autoclean;

has nombre  => (is => 'ro', isa => Str, required => 1);
has email => (is => 'ro', isa => Str, required => 1);
has edad   => (is => 'ro', isa => Int, default  => sub { 0 });
has roles => (is => 'ro', isa => ArrayRef[Str], default => sub { [] });

sub es_admin($self) {
    return grep { $_ eq 'admin' } $self->roles->@*;
}

sub saludar($self) {
    return "Hola, soy " . $self->nombre;
}

1;

# Uso
my $usuario = Usuario->new(
    nombre  => 'Alicia',
    email => '[email protected]',
    roles => ['admin', 'usuario'],
);

# Mal: Hashref bendecido (sin validación, sin accesores)
package Usuario;
sub new {
    my ($clase, %args) = @_;
    return bless \%args, $clase;
}
sub nombre { return $_[0]->{nombre} }
1;

Roles Moo

package Rol::Serializable;
use Moo::Role;
use JSON::MaybeXS qw(encode_json);
requires 'TO_HASH';
sub to_json($self) { encode_json($self->TO_HASH) }
1;

package Usuario;
use Moo;
with 'Rol::Serializable';
has nombre  => (is => 'ro', required => 1);
has email => (is => 'ro', required => 1);
sub TO_HASH($self) { { nombre => $self->nombre, email => $self->email } }
1;

Palabra Clave Nativa class (5.38+, Corinna)

use v5.38;
use feature 'class';
no warnings 'experimental::class';

class Punto {
    field $x :param;
    field $y :param;
    method magnitud() { sqrt($x**2 + $y**2) }
}

my $p = Punto->new(x => 3, y => 4);
say $p->magnitud;  # 5

Expresiones Regulares

Capturas Nombradas y Bandera /x

use v5.36;

# Bien: Capturas nombradas con /x para legibilidad
my $log_re = qr{
    ^ (?<marca_tiempo> \d{4}-\d{2}-\d{2} \s \d{2}:\d{2}:\d{2} )
    \s+ \[ (?<nivel> \w+ ) \]
    \s+ (?<mensaje> .+ ) $
}x;

if ($linea =~ $log_re) {
    say "Tiempo: $+{marca_tiempo}, Nivel: $+{nivel}";
    say "Mensaje: $+{mensaje}";
}

# Mal: Capturas posicionales (difícil de mantener)
if ($linea =~ /^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\s+\[(\w+)\]\s+(.+)$/) {
    say "Tiempo: $1, Nivel: $2";
}

Patrones Precompilados

use v5.36;

# Bien: Compilar una vez, usar muchas
my $email_re = qr/^[A-Za-z0-9._%+-]+\@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;

sub validar_emails(@emails) {
    return grep { $_ =~ $email_re } @emails;
}

Estructuras de Datos

Referencias y Acceso Profundo Seguro

use v5.36;

# Referencias a hash y array
my $config = {
    base_de_datos => {
        host => 'localhost',
        puerto => 5432,
        opciones => ['utf8', 'sslmode=require'],
    },
};

# Acceso profundo seguro (devuelve undef si falta algún nivel)
my $puerto = $config->{base_de_datos}{puerto};           # 5432
my $faltante = $config->{cache}{host};           # undef, sin error

# Rebanadas de hash
my %subconjunto;
@subconjunto{qw(host puerto)} = @{$config->{base_de_datos}}{qw(host puerto)};

# Rebanadas de array
my @primeros_dos = $config->{base_de_datos}{opciones}->@[0, 1];

# Bucle for de múltiples variables (experimental en 5.36, estable en 5.40)
use feature 'for_list';
no warnings 'experimental::for_list';
for my ($clave, $valor) (%$config) {
    say "$clave => $valor";
}

E/S de Archivos

Open de Tres Argumentos

use v5.36;

# Bien: Open de tres argumentos con autodie (módulo central, elimina 'or die')
use autodie;

sub leer_archivo($ruta) {
    open my $fh, '<:encoding(UTF-8)', $ruta;
    local $/;
    my $contenido = <$fh>;
    close $fh;
    return $contenido;
}

# Mal: Open de dos argumentos (riesgo de inyección de shell, ver perl-security)
open FH, $ruta;            # NUNCA hagas esto
open FH, "< $ruta";        # Sigue siendo malo — datos de usuario en la cadena de modo

Path::Tiny para Operaciones con Archivos

use v5.36;
use Path::Tiny;

my $archivo = path('config', 'app.json');
my $contenido = $archivo->slurp_utf8;
$archivo->spew_utf8($nuevo_contenido);

# Iterar directorio
for my $hijo (path('src')->children(qr/\.pl$/)) {
    say $hijo->basename;
}

Organización de Módulos

Diseño Estándar de Proyectos

MiApp/
├── lib/
│   └── MiApp/
│       ├── App.pm           # Módulo principal
│       ├── Config.pm        # Configuración
│       ├── DB.pm            # Capa de base de datos
│       └── Util.pm          # Utilidades
├── bin/
│   └── miapp                # Script de punto de entrada
├── t/
│   ├── 00-load.t            # Pruebas de compilación
│   ├── unit/                # Pruebas unitarias
│   └── integration/         # Pruebas de integración
├── cpanfile                 # Dependencias
├── Makefile.PL              # Sistema de construcción
└── .perlcriticrc            # Configuración de linting

Patrones de Exporter

package MiApp::Util;
use v5.36;
use Exporter 'import';

our @EXPORT_OK   = qw(recortar);
our %EXPORT_TAGS = (todas => \@EXPORT_OK);

sub recortar($str) { $str =~ s/^\s+|\s+$//gr }

1;

Herramientas

Configuración de perltidy (.perltidyrc)

-i=4        # Sangría de 4 espacios
-l=100      # Longitud de línea de 100 caracteres
-ci=4       # Sangría de continuación
-ce         # else acurrucado
-bar        # Llave de apertura en la misma línea
-nolq       # No sangrar cadenas largas entre comillas

Configuración de perlcritic (.perlcriticrc)

severity = 3
theme = core + pbp + security

[InputOutput::RequireCheckedSyscalls]
functions = :builtins
exclude_functions = say print

[Subroutines::ProhibitExplicitReturnUndef]
severity = 4

[ValuesAndExpressions::ProhibitMagicNumbers]
allowed_values = 0 1 2 -1

Gestión de Dependencias (cpanfile + carton)

cpanm App::cpanminus Carton   # Instalar herramientas
carton install                 # Instalar dependencias desde cpanfile
carton exec -- perl bin/miapp  # Ejecutar con dependencias locales
# cpanfile
requires 'Moo', '>= 2.005';
requires 'Path::Tiny';
requires 'JSON::MaybeXS';
requires 'Try::Tiny';

on test => sub {
    requires 'Test2::V0';
    requires 'Test::MockModule';
};

Referencia Rápida: Modismos Perl Modernos

Patrón HeredadoReemplazo Moderno
use strict; use warnings;use v5.36;
my ($x, $y) = @_;sub foo($x, $y) { ... }
@{ $ref }$ref->@*
%{ $ref }$ref->%*
open FH, "< $file"open my $fh, '<:encoding(UTF-8)', $file
hashref bendecidoclase Moo con tipos
$1, $2, $3$+{nombre} (capturas nombradas)
eval { }; if ($@)Try::Tiny o try/catch nativo (5.40+)
BEGIN { require Exporter; }use Exporter 'import';
Operaciones manuales de archivosPath::Tiny
blessed($o) && $o->isa('X')$o isa 'X' (5.32+)
builtin::true / falseuse builtin 'true', 'false'; (5.36+, experimental)

Anti-Patrones

# 1. Open de dos argumentos (riesgo de seguridad)
open FH, $nombre_archivo;                     # NUNCA

# 2. Sintaxis de objeto indirecto (análisis ambiguo)
my $obj = new Foo(bar => 1);            # Mal
my $obj = Foo->new(bar => 1);           # Bien

# 3. Dependencia excesiva de $_
map { procesar($_) } grep { validar($_) } @items;  # Difícil de seguir
my @validos = grep { validar($_) } @items;           # Mejor: dividir
my @resultados = map { procesar($_) } @validos;

# 4. Deshabilitar strict refs
no strict 'refs';                        # Casi siempre está mal
${"Mi::Paquete::$var"} = $valor;         # Usa un hash en su lugar

# 5. Variables globales como configuración
our $TIMEOUT = 30;                       # Mal: global mutable
use constant TIMEOUT => 30;              # Mejor: constante
# Mejor: Atributo Moo con valor predeterminado

# 6. Evaluación de cadena para cargar módulos
eval "require $module";                  # Mal: riesgo de inyección de código
eval "use $module";                      # Mal
use Module::Runtime 'require_module';    # Bien: carga segura de módulos
require_module($module);

Recuerda: El Perl moderno es limpio, legible y seguro. Deja que use v5.36 maneje el código repetitivo, usa Moo para objetos y prefiere los módulos probados de CPAN sobre soluciones hechas a mano.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

Skills relacionados