2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

coffeescript/ harmonyのdestrucutring assignmentをperlでやる。

Posted at

cpanizeはしてないけど、とりあえずgithubにはあげた。
https://github.com/hirokidaichi/p5-Data-Destructuring-Assignment

分割代入ってなにかというと"分割"して "代入"できるという機能です。

futurists =
  sculptor: "Umberto Boccioni"
  painter:  "Vladimir Burliuk"
  poet:
    name:   "F.T. Marinetti"
    address: [
      "Via Roma 42R"
      "Bellagio, Italy 22021"
    ]
// 1行で変数に構造を写像できる
{poet: {name, address: [street, city]}} = futurists

詳しくは
http://coffeescript.org/#destructuring
ここを参照

これが慣れてくると以外と便利なんだけど、
perlの黒魔術で実現したいなと言うことで、皆さん大好きlvalueとtieを使って、次のようなことができるモジュールを作ってみた。


destruct([\my $hoge,\my $fuga]) = [10,20];
print "hoge is $hoge";# hoge is 10
print "fuga is $fuga";# fuga is 20

こんな風に左辺に構造をもって、右辺の構造とマッチングして、代入することができます。

destruct( \my $hoge ) = 10;

変数はリファレンスで渡してください。

destruct( [\ $a ,\ $b] ) = [$b,$a];

swapもこんなに簡単。


destruct( { hash => \my $hash } ) = { hash => [1,2,3]};

hashrefもできます。

my @array =  map{ +{ hoge => "$_",fuga => $_ * 2}} (1..10);

while(destruct({ hoge => \my $hoge } ) = shift @array) {
    # $hoge..;
}

while句の中で。

my @array =  map{ +{ hoge => "$_",fuga => $_ * 2}} (1..10);
for my $elem (@array){
    destruct({ hoge => \my $hoge, fuga => \my $fuga}) = $elem;
}

for文とともに

my $template = { hoge => 1,fuga => 2};
if( destruct({ hoge => \my $hoge ,piyo => \my $fuga }) = $template ){
    ::pass 'matched any';
}else {
    # not come here
}

if文の中ではこう。一個でもmatchするとtrueです。

2
3
0

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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?