LoginSignup
5
4

More than 5 years have passed since last update.

進捗どうですかブーム???に Perl でのりかかる

Last updated at Posted at 2015-07-17

「進捗・どう・です・か」をランダムに表示し「進捗どうですか」が完成したら煽ってくるClojure
「進捗・どう・です・か」をランダムに表示し「進捗どうですか」が完成したら煽ってくるプログラム
「進捗・どう・です・か」をHaskellで書いてみた
進捗どうですかブーム?にrubyでのっかってみる
進捗どうですかブーム??にPythonでのりかかってみる
進捗どうですかブーム???にShellScriptで挑むフリしてExpectに逃げる

とりあえず愚直に移植。

はい、普通すぎて何も面白くありませんね。

shinchoku.pl
#!env perl

use utf8;
use strict;
use warnings;

binmode(STDOUT, ":utf8");
$|=1;

our @words =qw/進捗 どう です か/;
our $count = scalar @words;
our $end_word = qq/???/;

{
  my $length = 0;
  my $sorted = 0;
  my $last_idx = 0;
  while ( $sorted != $count -1 ) {
    my $idx = int(rand($count));
    my $word = $words[$idx];
    print $word;
    $length += length($word);
    $sorted = $idx > $last_idx ? $sorted +1 : 0;
    $last_idx = $idx;
  }
  print $end_word;
  $length += length $end_word;
  printf "\n%d文字で煽られました\n", $length;
}

もっと Perl らしさを前面に出したいですがどうするのが良いでしょう。
しばらく書いていなかったのでカンが鈍っていて困ります。

末尾再帰最適化 ver を書いてみた。

shinchoku.pl
#!env perl

use utf8;
use strict;
use warnings;

binmode(STDOUT, ":utf8");

use Object::String;

package Object::String;

use overload qq/""/ => \&to_string;

package Object::Array;

use overload qq|<=>| => sub { $_[0]->size <=> $_[1]->size } ;

sub pick {
    my $self = $_[0];
    $self->elem(int(rand($self->size)));
}

# ここまでおまじない

package Main;

use Object::String qw/str/;
use Object::Array qw/Array/;

our $words = Array([qw/進捗 どう です か/])->map(sub{ str($_); });
our $end_word = str(qq/???/);

{
  my $length = 0;
  my $cache  = Array();
  my $calc;
  $calc = sub {
    print my $word = $words->pick;
    $length += $word->length;

    $cache->push($word);
    $cache->shift while $cache > $words;

    if ( "@{$words}" eq "@{$cache}" ) {
        return;
    } else {
       goto &$calc;
    }
  };
  $calc->();
  print $end_word;
  $length += $end_word->length;
  printf "\n%d文字で煽られました\n", $length;
}

配列のもうちょっと小綺麗なモジュールがあれば……
ちょっとマシになったけれど機能不足でおまじないが多くなってしまった。

5
4
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
5
4