跳转至

现代 Perl 开发模式

用于构建健壮且可维护的应用程序的惯用 Perl 5.36+ 模式和最佳实践。

激活时机

  • 编写新的 Perl 代码或模块时
  • 审查 Perl 代码以符合惯用法时
  • 将传统 Perl 重构为现代标准时
  • 设计 Perl 模块架构时
  • 将 5.36 之前的代码迁移到现代 Perl 时

工作原理

将这些模式作为现代 Perl 5.36+ 的默认偏好来应用:签名、显式模块、集中式错误处理、可测试边界。以下示例旨在作为起点复制,并根据当前实际应用、依赖栈和部署模型进行适配。

核心原则

1. 使用 v5.36 语法

单个 use v5.36 可替代旧的样板代码,并启用 strict、warnings 和子程序签名。

# Good: モダンなプリアンブル
use v5.36;

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

# Bad: レガシーな定型文
use strict;
use warnings;
use feature 'say', 'signatures';
no warnings 'experimental::signatures';

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

2. 子程序签名

使用签名以提高清晰度并自动进行参数数量检查。

use v5.36;

# Good: デフォルト値付きシグネチャ
sub connect_db($host, $port = 5432, $timeout = 30) {
    # $hostは必須、その他はデフォルトあり
    return DBI->connect("dbi:Pg:host=$host;port=$port", undef, undef, {
        RaiseError => 1,
        PrintError => 0,
    });
}

# Good: 可変引数のためのスラーピーパラメータ
sub log_message($level, @details) {
    say "[$level] " . join(' ', @details);
}

# Bad: 手動引数アンパック
sub connect_db {
    my ($host, $port, $timeout) = @_;
    $port    //= 5432;
    $timeout //= 30;
    # ...
}

3. 上下文敏感性

理解标量上下文与列表上下文——Perl 的核心概念。

use v5.36;

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

my @copy  = @items;            # リストコンテキスト: すべての要素
my $count = @items;            # スカラーコンテキスト: カウント (5)
say "Items: " . scalar @items; # スカラーコンテキストを強制

4. 后置解引用

在嵌套结构中使用后置解引用语法以提高可读性。

use v5.36;

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

# Good: 後置逆参照
my @users = $data->{users}->@*;
my @roles = $data->{users}[0]{roles}->@*;
my %first = $data->{users}[0]->%*;

# Bad: 前置逆参照(チェーンで読みにくい)
my @users = @{ $data->{users} };
my @roles = @{ $data->{users}[0]{roles} };

5. isa 运算符(5.32+)

中缀类型检查——替代 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 的现代面向对象

对于轻量且现代的面向对象编程,优先使用 Moo。仅在需要元协议时使用 Moose。

# Good: 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 => 'alice@example.com',
    roles => ['admin', 'user'],
);

# Bad: ブレスされた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;

# Good: 読みやすさのための/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}";
}

# Bad: 位置キャプチャ(メンテが難しい)
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;

# Good: 1回コンパイル、複数回使用
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";
}

文件 I/O

三参数 open

use v5.36;

# Good: autodieを使った3引数open(コアモジュール、'or die'を排除)
use autodie;

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

# Bad: 2引数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            # リンティング設定

导出器模式

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';
};

快速参考:现代 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 / false use builtin 'true', 'false';(5.36+,实验性)

反模式

# 1. 2引数open(セキュリティリスク)
open FH, $filename;                     # 絶対にしない

# 2. 間接オブジェクト構文(あいまいな解析)
my $obj = new Foo(bar => 1);            # Bad
my $obj = Foo->new(bar => 1);           # Good

# 3. $_への過度の依存
map { process($_) } grep { validate($_) } @items;  # 追うのが難しい
my @valid = grep { validate($_) } @items;           # より良い: 分割する
my @results = map { process($_) } @valid;

# 4. strictリファレンスの無効化
no strict 'refs';                        # ほぼ常に間違い
${"My::Package::$var"} = $value;         # 代わりにhashを使用

# 5. グローバル変数を設定として使用
our $TIMEOUT = 30;                       # Bad: 可変グローバル
use constant TIMEOUT => 30;              # Better: 定数
# Best: デフォルト付きのMoo属性

# 6. モジュールロードのための文字列eval
eval "require $module";                  # Bad: コードインジェクションリスク
eval "use $module";                      # Bad
use Module::Runtime 'require_module';    # Good: 安全なモジュールロード
require_module($module);

记住:现代 Perl 简洁、易读且安全。让 use v5.36 处理样板代码,对象使用 Moo,并优先选择 CPAN 上久经考验的模块,而不是自造方案。

本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 ev/ECC