Communitygithub.com

perl-patterns

Perl 5.36+ 최신 관용구, 모범 사례 및 규칙 - 강력하고 유지보수 가능한 Perl 애플리케이션을 구축할 때 사용합니다.

perl-patterns란 무엇인가요?

이 스킬은 Modern Perl (5.36 이상) 개발을 위한 포괄적인 패턴 및 모범 사례 가이드입니다. `use v5.36` 프라그마, 서브루틴 시그니처, 후위 역참조(postfix dereferencing), `isa` 연산자 등 Perl의 최신 문법을 활용해 더 깔끔하고 안전한 코드를 작성하는 방법을 알려줍니다. 오류 처리는 `eval/die`, `Try::Tiny`, 그리고 5.40 이상에서 사용 가능한 네이티브 `try/catch`를 다루며, Moo를 이용한 현대적인 객체 지향 설계와 정규식 명명 캡처(named captures)와 `/x` 플래그 사용법도 포함합니다. 또한 파일 I/O (`Path::Tiny`), 모듈 구성, 린팅 도구(`perltidy`, `perlcritic`), 의존성 관리(`cpanfile` + `Carton`) 등 전체 개발 생태계를 아우르며, 일반적인 안티 패턴(예: two-arg open, 간접 객체 문법)도 경고합니다. 이 스킬은 Claude Code, Cursor, Codex 등 AI 에이전트가 새로운 Perl 코드를 작성하거나 기존 코드를 리팩토링할 때 참고할 수 있도록 설계되었습니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/perl-patterns

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

Modern Perl 개발 패턴

관용적인 Perl 5.36+ 패턴과 모범 사례: 강력하고 유지보수 가능한 애플리케이션을 구축하기 위한 가이드입니다.

사용 시점

  • 새로운 Perl 코드나 모듈을 작성할 때
  • Perl 코드를 관용구 준수 여부로 검토할 때
  • 레거시 Perl을 최신 표준으로 리팩토링할 때
  • Perl 모듈 아키텍처를 설계할 때
  • 5.36 미만 코드를 현대적인 Perl로 마이그레이션할 때

작동 방식

이 패턴들은 Modern Perl 5.36+의 기본값(시그니처, 명시적 모듈, 집중된 오류 처리, 테스트 가능한 경계) 쪽으로 바이어스를 적용합니다. 아래 예제는 시작점으로 복사한 후, 실제 앱, 의존성 스택, 배포 모델에 맞게 조정하세요.

핵심 원칙

1. use v5.36 프라그마 사용

use v5.36 하나만으로 기존의 여러 설정을 대체하며 strict, warnings, 서브루틴 시그니처를 활성화합니다.

# 좋음: 현대적인 프리앰블
use v5.36;

sub greet($name) {
    say "Hello, $name!";
}

# 나쁨: 레거시 설정
use strict;
use warnings;
use feature 'say', 'signatures';
no warnings 'experimental::signatures';

sub greet {
    my ($name) = @_;
    say "Hello, $name!";
}

2. 서브루틴 시그니처

시그니처를 사용하면 명확성과 자동 인자 개수 검사를 얻을 수 있습니다.

use v5.36;

# 좋음: 기본값이 있는 시그니처
sub connect_db($host, $port = 5432, $timeout = 30) {
    # $host는 필수, 나머지는 기본값
    return DBI->connect("dbi:Pg:host=$host;port=$port", undef, undef, {
        RaiseError => 1,
        PrintError => 0,
    });
}

# 좋음: 가변 인자를 위한 slurpy 매개변수
sub log_message($level, @details) {
    say "[$level] " . join(' ', @details);
}

# 나쁨: 수동 인자 언패킹
sub connect_db {
    my ($host, $port, $timeout) = @_;
    $port    //= 5432;
    $timeout //= 30;
    # ...
}

3. 컨텍스트 민감성

스칼라 vs 리스트 컨텍스트를 이해하는 것은 Perl의 핵심 개념입니다.

use v5.36;

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

my @copy  = @items;            # 리스트 컨텍스트: 모든 요소
my $count = @items;            # 스칼라 컨텍스트: 개수 (5)
say "Items: " . scalar @items; # 강제 스칼라 컨텍스트

4. 후위 역참조 (Postfix Dereferencing)

중첩 구조에서 가독성을 위해 후위 역참조 문법을 사용합니다.

use v5.36;

my $data = {
    users => [
        { name => 'Alice', roles => ['admin', 'user'] },
        { name => 'Bob',   roles => ['user'] },
    ],
};

# 좋음: 후위 역참조
my @users = $data->{users}->@*;
my @roles = $data->{users}[0]{roles}->@*;
my %first = $data->{users}[0]->%*;

# 나쁨: 둘러싸는 역참조 (체인에서 읽기 어려움)
my @users = @{ $data->{users} };
my @roles = @{ $data->{users}[0]{roles} };

5. isa 연산자 (5.32+)

중위(infix) 타입 검사 - blessed($o) && $o->isa('X')를 대체합니다.

use v5.36;
if ($obj isa 'My::Class') { $obj->do_something }

오류 처리

eval/die 패턴

use v5.36;

sub parse_config($path) {
    my $content = eval { path($path)->slurp_utf8 };
    die "Config error: $@" if $@;
    return decode_json($content);
}

Try::Tiny (신뢰할 수 있는 예외 처리)

use v5.36;
use Try::Tiny;

sub fetch_user($id) {
    my $user = try {
        $db->resultset('User')->find($id)
            // die "User $id not found\n";
    }
    catch {
        warn "Failed to fetch user $id: $_";
        undef;
    };
    return $user;
}

네이티브 try/catch (5.40+)

use v5.40;

sub divide($x, $y) {
    try {
        die "Division by zero" if $y == 0;
        return $x / $y;
    }
    catch ($e) {
        warn "Error: $e";
        return;
    }
}

Moo를 활용한 현대적 OO

가벼우면서도 현대적인 OO를 위해 Moo를 선호하세요. 메타프로토콜이 필요한 경우에만 Moose를 사용합니다.

# 좋음: Moo 클래스
package User;
use Moo;
use Types::Standard qw(Str Int ArrayRef);
use namespace::autoclean;

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

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

sub greet($self) {
    return "Hello, I'm " . $self->name;
}

1;

# 사용법
my $user = User->new(
    name  => 'Alice',
    email => '[email protected]',
    roles => ['admin', 'user'],
);

# 나쁨: Blessed hashref (검증도, 접근자도 없음)
package User;
sub new {
    my ($class, %args) = @_;
    return bless \%args, $class;
}
sub name { return $_[0]->{name} }
1;

Moo 역할

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

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

네이티브 class 키워드 (5.38+, Corinna)

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

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

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

정규 표현식

명명 캡처와 /x 플래그

use v5.36;

# 좋음: 가독성을 위한 명명 캡처 + /x
my $log_re = qr{
    ^ (?<timestamp> \d{4}-\d{2}-\d{2} \s \d{2}:\d{2}:\d{2} )
    \s+ \[ (?<level> \w+ ) \]
    \s+ (?<message> .+ ) $
}x;

if ($line =~ $log_re) {
    say "Time: $+{timestamp}, Level: $+{level}";
    say "Message: $+{message}";
}

# 나쁨: 위치 기반 캡처 (유지보수 어려움)
if ($line =~ /^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\s+\[(\w+)\]\s+(.+)$/) {
    say "Time: $1, Level: $2";
}

사전 컴파일된 패턴

use v5.36;

# 좋음: 한 번 컴파일해서 여러 번 사용
my $email_re = qr/^[A-Za-z0-9._%+-]+\@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;

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

자료 구조

참조와 안전한 깊은 접근

use v5.36;

# 해시와 배열 참조
my $config = {
    database => {
        host => 'localhost',
        port => 5432,
        options => ['utf8', 'sslmode=require'],
    },
};

# 안전한 깊은 접근 (중간 단계가 없으면 undef 반환)
my $port = $config->{database}{port};           # 5432
my $missing = $config->{cache}{host};           # undef, 오류 없음

# 해시 슬라이스
my %subset;
@subset{qw(host port)} = @{$config->{database}}{qw(host port)};

# 배열 슬라이스
my @first_two = $config->{database}{options}->@[0, 1];

# 다중 변수 for 루프 (5.36에서 실험적, 5.40에서 안정)
use feature 'for_list';
no warnings 'experimental::for_list';
for my ($key, $val) (%$config) {
    say "$key => $val";
}

파일 입출력

세-인자 open

use v5.36;

# 좋음: autodie와 함께 세-인자 open (핵심 모듈, 'or die' 불필요)
use autodie;

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

# 나쁨: 두-인자 open (쉘 인젝션 위험, perl-security 참고)
open FH, $path;            # 절대 이렇게 하지 마세요
open FH, "< $path";        # 여전히 나쁨 — 모드 문자열에 사용자 데이터 포함

파일 작업을 위한 Path::Tiny

use v5.36;
use Path::Tiny;

my $file = path('config', 'app.json');
my $content = $file->slurp_utf8;
$file->spew_utf8($new_content);

# 디렉터리 순회
for my $child (path('src')->children(qr/\.pl$/)) {
    say $child->basename;
}

모듈 구성

표준 프로젝트 레이아웃

MyApp/
├── lib/
│   └── MyApp/
│       ├── App.pm           # 메인 모듈
│       ├── Config.pm        # 설정
│       ├── DB.pm            # 데이터베이스 계층
│       └── Util.pm          # 유틸리티
├── bin/
│   └── myapp                # 진입점 스크립트
├── t/
│   ├── 00-load.t            # 컴파일 테스트
│   ├── unit/                # 단위 테스트
│   └── integration/         # 통합 테스트
├── cpanfile                 # 의존성
├── Makefile.PL              # 빌드 시스템
└── .perlcriticrc            # 린팅 설정

Exporter 패턴

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

our @EXPORT_OK   = qw(trim);
our %EXPORT_TAGS = (all => \@EXPORT_OK);

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

1;

도구

perltidy 설정 (.perltidyrc)

-i=4        # 4-공백 들여쓰기
-l=100      # 100자 행 길이
-ci=4       # 연속 들여쓰기
-ce         # cuddled else
-bar        # 여는 중괄호를 같은 줄에
-nolq       # 긴 따옴표 문자열 내어쓰기하지 않음

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

의존성 관리 (cpanfile + carton)

cpanm App::cpanminus Carton   # 도구 설치
carton install                 # cpanfile에서 의존성 설치
carton exec -- perl bin/myapp  # 로컬 의존성으로 실행
# cpanfile
requires 'Moo', '>= 2.005';
requires 'Path::Tiny';
requires 'JSON::MaybeXS';
requires 'Try::Tiny';

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

빠른 참조: Modern Perl 관용구

레거시 패턴현대적 대체
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
blessed hashref타입을 가진 Moo 클래스
$1, $2, $3$+{name} (명명 캡처)
eval { }; if ($@)Try::Tiny 또는 네이티브 try/catch (5.40+)
BEGIN { require Exporter; }use Exporter 'import';
수동 파일 연산Path::Tiny
blessed($o) && $o->isa('X')$o isa 'X' (5.32+)
builtin::true / falseuse builtin 'true', 'false'; (5.36+, 실험적)

안티 패턴

# 1. 두-인자 open (보안 위험)
open FH, $filename;                     # 절대 하지 마세요

# 2. 간접 객체 문법 (모호한 파싱)
my $obj = new Foo(bar => 1);            # 나쁨
my $obj = Foo->new(bar => 1);           # 좋음

# 3. $_에 대한 과도한 의존
map { process($_) } grep { validate($_) } @items;  # 따라가기 어려움
my @valid = grep { validate($_) } @items;           # 더 나음: 나누기
my @results = map { process($_) } @valid;

# 4. strict refs 비활성화
no strict 'refs';                        # 거의 항상 잘못됨
${"My::Package::$var"} = $value;        # 대신 해시 사용

# 5. 전역 변수를 설정으로 사용
our $TIMEOUT = 30;                       # 나쁨: 변경 가능한 전역
use constant TIMEOUT => 30;              # 더 나음: 상수
# 최고: 기본값을 가진 Moo 속성

# 6. 모듈 로딩을 위한 문자열 eval
eval "require $module";                  # 나쁨: 코드 인젝션 위험
eval "use $module";                      # 나쁨
use Module::Runtime 'require_module';    # 좋음: 안전한 모듈 로딩
require_module($module);

기억하세요: Modern Perl은 깨끗하고, 읽기 쉽고, 안전합니다. use v5.36으로 설정 상용구를 처리하고, 객체에는 Moo를 사용하며, 직접 구현보다는 CPAN의 검증된 모듈을 선호하세요.

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/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

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.

관련 스킬