LoginSignup
22
12

More than 3 years have passed since last update.

2019年の最先端のPerl開発ボイラープレート

Last updated at Posted at 2019-12-01

Perl Advent Calendar始まりました! @AnaTofuZ ありがとうございます!
今年も元気にやっていきましょう!

さて、Perlも実はまだまだ進化しています。

今年はPerl6として開発されていた言語がRakuに名前を変えましたが、
Perl5はPerlとして今後も開発とメンテナンスが続けられていきます。

2019年にPerlを書くそこのあなた、最先端のものが必ずしも現場にマッチするとは限らないですが、最先端のものの多くは既存のものにある課題を解決しています。
どういったものをどう使って書けばよいのかなんとなく知っておくといざというときの助けになるでしょう。

前提

このへんつかっとくといいとおもいます

  • strictures
    • use strict だけでなく様々な強い制約を有効化します。 PERL_STRICTURES_EXTRA をtrueにしておけば no indirect とかもやってくれる。
  • Syntax::Keyword::Try
    • try/catch/finally あたりのsyntaxをkeyword pluginで提供してくれる。Try::Tiny などのprototype式のやり方と比較してハマりどころが少ないと思われる。
  • Function::Parameters
    • fun/method あたりのsyntaxをkeyword pluginで提供してくれる。後述のTypes::Standardと組み合わせて動的型チェックもできる。
  • Function::Return
    • Function::Parametersが引数を見るならこっちは返り値を見るぜというやつ。
  • Type::Tiny
    • ナウなヤングにバカウケな型表現メタオブジェクト。最近のPerlでのデファクトスタンダード。
  • Types::Standard
    • Type::Tinyに同梱されている基本型の定義セット。
  • Moo
    • ナウなヤングにバカウケなOOPフレームワーク。最近のPerlでのデファクトスタンダード。
  • namespace::clean
    • 外部からインポートしてきたサブルーチンをBEGINフェーズ終了時に掃除してくれる。うっかり外部から行儀悪く参照するみたいなことができなくなって便利。

詳しくはマニュアルを読みましょう

ボイラープレート

詳しいことはきっと誰かが書いてくれる!!!!

scripting

use strictures 2;
use Syntax::Keyword::Try;
use Function::Parameters;
use Function::Return;
use Types::Standard -types;
use namespace::clean;

fun main(Str $msg) {
    say "Hello, $msg";
}

main(@ARGV);

OOP

package Point;
use strictures 2;
use Moo;
use Syntax::Keyword::Try;
use Function::Parameters;
use Function::Return;
use Types::Standard -types;
use namespace::clean;

1;

package Point;
use strictures 2;
use Moo;
use Syntax::Keyword::Try;
use Function::Parameters;
use Function::Return;
use Types::Standard -types;
use Type::Tiny::Class;
use namespace::clean;

has x => (
    is  => 'ro',
    isa => Int,
);

has y => (
    is  => 'ro',
    isa => Int,
);

method distance_of((InstanceOf['Point']) $dest) :Return(InstanceOf['Point']) {
    my $distance_x = $dest->x - $self->x;
    my $distance_y = $dest->y - $self->y;
    return Point->new(x => $distance_x, y => $distance_y);
}

method as_string() :Return(Str) {
    return sprintf 'Point(%d, %d)', $self->x, $self->y;
}

1;

おまけ

Function::Parametersで (InstanceOf['Point']) と括弧でくくる必要がある件はissueが立っていましたがいまのところ直す動きではなさそうです

https://github.com/mauke/Function-Parameters/issues/36

追記: @kfly8 による解説がなされました
22
12
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
12