中小企業のマーケティングやブランディングのコンサルティング。事業運営、組織運営のPDCA改善やホームページの制作、ウェブサイト改善などITネット活用を中心にサービスを提供しています。

Perl6のプログラミング環境「Rapid Perl6」を作りました

バージョン1.0 を今年 2015年 のクリスマスにリリースすると発表があった Perl 6.0。かれこれ 10 年以上開発していてなかなかリリースされなかったがようやく形になりそう。

一足早くその Perl 6 のプログラミング環境をサクッと立ち上げられる Vagrant 環境をつくりました。

Perl 6 は言語仕様も変わり、Perl 5 など前バージョンの後方互換性もないので、新しい言語と見ていろいろいじってみたい方はどうぞ。

以下、GitHub にある Rapid Perl6 の readme-ja.md です。


Rapid Perl6

Rapid Perl6 is Vagrant environment for the Perl 6 programming language.

Provisioning

# install Vagrant plugin
vagrant plugin install vagrant-hostsupdater
cd rapid-perl6
vagrant up
...
vagrant ssh

Version

cd /home/vagrant/perl6/bin
./perl6 -v
This is perl6 version 2015.01-194-g5bb1942 built on MoarVM version 2015.01-72-g9106bee

OR

cd /home/vagrant/perl6/bin
./perl6 -V
...

Help

cd /home/vagrant/perl6/bin
./perl6 -h

hello world!

cd /home/vagrant/perl6/bin
./perl6
> say 'hello world!';
hello world!
> exit;

hello world! (helloworld.pl)

#!/usr/bin/env perl6
say q/hello world!/;
1;

Run helloworld.pl

cd /home/vagrant/perl6/bin
./perl6 /vagrant/helloworld.pl
hello world!

Reference

Perl で OAuth / モジュール OAuth::Lite::Consumer インストール

Twitter や Facebook などウェブサービスの連携には欠かせなくなりつつある認証システム OAuth (オー オース)。アプリ開発者としてマスターしておきたい認証システムのひとつ。今回モジュール OAuth::Lite::Consumer をインストールして、Perlで OAuth 認証できる環境をつくってみた。Twitter で認証してアカウント情報を表示するサンプルプログラムも。

OAuth::Lite::Consumer インストール

ふつうに cpanm でインストールできず。パッケージ openssl-devel が必要。

cpanm OAuth::Lite::Consumer
...
Checking if you have Crypt::OpenSSL::RSA 0.25 ... No
Checking if you have Crypt::OpenSSL::Random 0.04 ... No
...

エラーで止まってしまう。パッケージがないので、perlモジュールの依存関係を解決できず。

まずは、パッケージ openssl-devel をインストール。

yum install openssl-devel

インストール後。

cpanm OAuth::Lite::Consumer

complete!!

サンプルプログラム

Twitter のアカウントでログイン認証。アクセストークンを取得して Twitter のアカウント情報を表示するサンプルプログラム。サンプルを動かすには Twitter にアプリケーションを登録して、ConsumerKey と ConsumerSecret を取得する必要があります。
登録は dev.twitter.com から。

流れとメソッド

  1. リクエストトークンを取得する – get_request_token()
  2. リクエストトークンを元に認証 – url_to_authorize()
  3. Twitterログイン画面でアプリ認証
  4. アプリ認証ボタンを押すと callback_url に転送 (リダイレクト)
  5. アクセストークンの取得 – get_access_token()
  6. アクセストークンを元に認証が必要なリクエスト (GET account/verify_credentials) を発行、今回Twitterアカウント情報を表示 – gen_oauth_request()
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use CGI;
use OAuth::Lite::Consumer;
use LWP::UserAgent;
use JSON;
my $ConsumerKey = 'xxxxxxx';
my $ConsumerSecret = 'xxxxxxxx';
my $callback_url = 'xxxxxxxx';
my $consumer = OAuth::Lite::Consumer->new(
consumer_key    => $ConsumerKey,
consumer_secret => $ConsumerSecret,
site => "http://twitter.com/",
request_token_path => "https://api.twitter.com/oauth/request_token",
access_token_path => "https://api.twitter.com/oauth/access_token",
authorize_path => "https://api.twitter.com/oauth/authorize",
callback_url => $callback_url,
);
my $query = CGI->new;
if ($query->param('oauth_token') && $query->param('oauth_verifier')) {
my $access_token = $consumer->get_access_token(
token => $query->param('oauth_token'),
verifier => $query->param('oauth_verifier'),
);
my $req = $consumer->gen_oauth_request(
method => 'GET',
url => 'http://api.twitter.com/1/account/verify_credentials.json',
token => $access_token,
);
my $ua = new LWP::UserAgent();
my $res = $ua->request($req);
die $res->status_line if ! $res->is_success;
my $account = decode_json($res->content);
print "Content-type: text/html;charset=UTF-8\n\n";
print "<img src='$account->{profile_image_url}' />";
print "<p>ID : $account->{id}</p>";
print "<p>name : $account->{name}</p>";
print "<p>screen_name : $account->{screen_name}</p>";
print "<p>description : $account->{description}</p>";
exit;
}
else {
my $request_token = $consumer->get_request_token();
my $uri = $consumer->url_to_authorize(
token => $request_token,
);
print $query->redirect($uri);
}
exit;

関連サイト

Net::Twitter が突然動かなくなったら (備忘メモ)

Net::Twitter が突然動かなくなった。なかなか気づかないエラーなので備忘メモ。

weaken is only available with the XS version of Scalar::Util at /usr/lib/perl5/site_perl/5.8.8/i386-linux-thread-multi/Class/MOP.pm line 12
BEGIN failed--compilation aborted at /usr/lib/perl5/site_perl/5.8.8/i386-linux-thread-multi/Class/MOP.pm line 12.
Compilation failed in require at /usr/lib/perl5/site_perl/5.8.8/i386-linux-thread-multi/Moose/Exporter.pm line 11.
BEGIN failed--compilation aborted at /usr/lib/perl5/site_perl/5.8.8/i386-linux-thread-multi/Moose/Exporter.pm line 11.
Compilation failed in require at /usr/lib/perl5/site_perl/5.8.8/i386-linux-thread-multi/Moose.pm line 14.
BEGIN failed--compilation aborted at /usr/lib/perl5/site_perl/5.8.8/i386-linux-thread-multi/Moose.pm line 14.
Compilation failed in require at /usr/lib/perl5/site_perl/5.8.8/Net/Twitter.pm line 2.

先頭に

weaken is only available with the XS version of Scalar::Util

とある。どうやら yum update で XS 版から Pure Perl 版の Scalar::Util に入れ替わったようだ。

weaken で Cコンパイラが使えないとエラーになって、Net::Twitter が玉突きのようなエラーに。

ということで、XS 版 Scalar::Util を再インストール。

$ sudo cpan
cpan> look Scalar::Util

でビルドディレクトリを作成して移動。オプション (-XS) を指定して Makefile を作成後、Scalar::Util をインストール。

$ perl Makefile.PL -XS
$ make
$ make test
$ make install

Complete!!

関連サイト

CPANの使い方 (シェルコマンド集)

CPAN (シーパン、Comprehensive Perl Archive Network) とは、Perlのライブラリ・モジュールや Perl で書かれたソフトウェアを集めた巨大なアーカイブ。世界中のPerlプログラマが開発したモジュールが簡単に入手でき、インストールすることができる。

CPAN シェル経由でPerlモジュールをインストールすると、他の依存しているモジュールもインストールしてくれるなど、手動でインストールするよりも作業が省けて効率的にインストールできます。

はじめての起動

$ perl -MCPAN -e shell

または、

$ cpan

初めてCPANを起動するとCPANを利用するにあたって設定します。設定はほぼ <Enter> を押すだけ。入力するのは最後のダウンロードサイトに関することだけ。

/usr/lib/perl5/5.8.8/CPAN/Config.pm initialized.
CPAN is the world-wide archive of perl resources. It consists of about
100 sites that all replicate the same contents all around the globe.
Many countries have at least one CPAN site already. The resources
found on CPAN are easily accessible with the CPAN.pm module. If you
want to use CPAN.pm, you have to configure it properly.
If you do not want to enter a dialog now, you can answer 'no' to this
question and I'll try to autoconfigure. (Note: you can revisit this
dialog anytime later by typing 'o conf init' at the cpan prompt.)
Are you ready for manual configuration? [yes]
The following questions are intended to help you with the
configuration. The CPAN module needs a directory of its own to cache
important index files and maybe keep a temporary mirror of CPAN files.
This may be a site-wide directory or a personal directory.
First of all, I'd like to create this directory. Where?
CPAN build and cache directory? [/root/.cpan]
If you want, I can keep the source files after a build in the cpan
home directory. If you choose so then future builds will take the
files from there. If you don't want to keep them, answer 0 to the
next question.
How big should the disk cache be for keeping the build directories
with all the intermediate files?
Cache size for build directory (in MB)? [10]
By default, each time the CPAN module is started, cache scanning
is performed to keep the cache size in sync. To prevent from this,
disable the cache scanning with 'never'.
Perform cache scanning (atstart or never)? [atstart]
To considerably speed up the initial CPAN shell startup, it is
possible to use Storable to create a cache of metadata. If Storable
is not available, the normal index mechanism will be used.
Cache metadata (yes/no)? [yes]
The next option deals with the charset your terminal supports. In
general CPAN is English speaking territory, thus the charset does not
matter much, but some of the aliens out there who upload their
software to CPAN bear names that are outside the ASCII range. If your
terminal supports UTF-8, you say no to the next question, if it
supports ISO-8859-1 (also known as LATIN1) then you say yes, and if it
supports neither nor, your answer does not matter, you will not be
able to read the names of some authors anyway. If you answer no, names
will be output in UTF-8.
Your terminal expects ISO-8859-1 (yes/no)? [yes]
If you have one of the readline packages (Term::ReadLine::Perl,
Term::ReadLine::Gnu, possibly others) installed, the interactive CPAN
shell will have history support. The next two questions deal with the
filename of the history file and with its size. If you do not want to
set this variable, please hit SPACE RETURN to the following question.
File to save your history? [/root/.cpan/histfile]
Number of lines to save? [100]
The CPAN module can detect when a module that which you are trying to
build depends on prerequisites. If this happens, it can build the
prerequisites for you automatically ('follow'), ask you for
confirmation ('ask'), or just ignore them ('ignore'). Please set your
policy to one of the three values.
Policy on building prerequisites (follow, ask or ignore)? [ask]
The CPAN module will need a few external programs to work properly.
Please correct me, if I guess the wrong path for a program. Don't
panic if you do not have some of them, just press ENTER for those. To
disable the use of a download program, you can type a space followed
by ENTER.
Where is your gzip program? [/bin/gzip]
Where is your tar program? [/bin/tar]
Where is your unzip program? [/usr/bin/unzip]
Where is your make program? [/usr/bin/make]
Where is your links program? [/usr/bin/links]
Where is your wget program? [/usr/bin/wget]
Warning: ncftpget not found in PATH
Where is your ncftpget program? []
Warning: ncftp not found in PATH
Where is your ncftp program? []
Where is your ftp program? [/usr/kerberos/bin/ftp]
Where is your gpg program? [/usr/bin/gpg]
What is your favorite pager program? [/usr/bin/less]
What is your favorite shell? [/bin/bash]
Every Makefile.PL is run by perl in a separate process. Likewise we
run 'make' and 'make install' in processes. If you have any
parameters (e.g. PREFIX, LIB, UNINST or the like) you want to pass
to the calls, please specify them here.
If you don't understand this question, just press ENTER.
Parameters for the 'perl Makefile.PL' command?
Typical frequently used settings:
PREFIX=~/perl       non-root users (please see manual for more hints)
Your choice:  []
Parameters for the 'make' command?
Typical frequently used setting:
-j3              dual processor system
Your choice:  []
Parameters for the 'make install' command?
Typical frequently used setting:
UNINST=1         to always uninstall potentially conflicting files
Your choice:  []
Sometimes you may wish to leave the processes run by CPAN alone
without caring about them. As sometimes the Makefile.PL contains
question you're expected to answer, you can set a timer that will
kill a 'perl Makefile.PL' process after the specified time in seconds.
If you set this value to 0, these processes will wait forever. This is
the default and recommended setting.
Timeout for inactivity during Makefile.PL? [0]
If you're accessing the net via proxies, you can specify them in the
CPAN configuration or via environment variables. The variable in
the $CPAN::Config takes precedence.
Your ftp_proxy?
Your http_proxy?
Your no_proxy?
You have no /root/.cpan/sources/MIRRORED.BY
I'm trying to fetch one
CPAN: LWP::UserAgent loaded ok
Fetching with LWP:
ftp://ftp.perl.org/pub/CPAN/MIRRORED.BY
Now we need to know where your favorite CPAN sites are located. Push
a few sites onto the array (just in case the first on the array won't
work). If you are mirroring CPAN to your local workstation, specify a
file: URL.
First, pick a nearby continent and country (you can pick several of
each, separated by spaces, or none if you just want to keep your
existing selections). Then, you will be presented with a list of URLs
of CPAN mirrors in the countries you selected, along with previously
selected URLs. Select some of those URLs, or just keep the old list.
Finally, you will be prompted for any extra URLs -- file:, ftp:, or
http: -- that host a CPAN mirror.
(1) Africa
(2) Asia
(3) Australasia
(4) Central America
(5) Europe
(6) North America
(7) Oceania
(8) South America
Select your continent (or several nearby continents) [] 2
Sorry! since you don't have any existing picks, you must make a
geographic selection.
(1) China
(2) Hong Kong
(3) India
(4) Indonesia
(5) Japan
(6) Kazakhstan
(7) Republic of Korea
(8) Russia
(9) Singapore
(10) Taiwan
(11) Thailand
(12) Turkey
Select your country (or several nearby countries) [] 5
Sorry! since you don't have any existing picks, you must make a
geographic selection.
(1) ftp://ftp.dti.ad.jp/pub/lang/CPAN/
(2) ftp://ftp.jaist.ac.jp/pub/CPAN/
(3) ftp://ftp.kddilabs.jp/CPAN/
(4) ftp://ftp.nara.wide.ad.jp/pub/CPAN/
(5) ftp://ftp.riken.jp/lang/CPAN/
(6) ftp://ftp.ring.gr.jp/pub/lang/perl/CPAN/
(7) ftp://ftp.u-aizu.ac.jp/pub/CPAN
(8) ftp://ftp.yz.yamagata-u.ac.jp/pub/lang/cpan/
Select as many URLs as you like (by number),
put them on one line, separated by blanks, e.g. '1 4 5' [] 1 2 3
Enter another URL or RETURN to quit: []
New set of picks:
ftp://ftp.dti.ad.jp/pub/lang/CPAN/
ftp://ftp.jaist.ac.jp/pub/CPAN/
ftp://ftp.kddilabs.jp/CPAN/

モジュールをインストール

cpan> install モジュール名

モジュールを更新する

cpan> upgrade モジュール名

CPAN 終了

cpan> q

または、

cpan> quit

ロックファイルが残っていてCPANが起動しない

There seems to be running another CPAN process (pid 26919).  Contacting...
Other job is running.
You may want to kill it and delete the lockfile, maybe. On UNIX try:
kill 26919
rm /root/.cpan/.lock

ロックファイルを削除してから、改めて起動。

$ rm /root/.cpan/.lock

CPAN のアップグレード

cpan> install Bundle::CPAN
...
インストール後
...
cpan> reload cpan

手動でPerlモジュールをインストール

CPANからモジュールのソースをダウンロードして、手動でPerlモジュールをインストール。Jcode.pmを例にとって。

$ cd $HOME
$ mkdir temp
$ cd temp
$ wget http://search.cpan.org/CPAN/authors/id/D/DA/DANKOGAI/Jcode-2.07.tar.gz
$ tar zxfv Jcode-2.07.tar.gz
$ cd Jcode-2.07
$ perl Makefile.PL
$ make
$ make test
$ make install

インストールの確認は、

# perl -e 'use Jcode;'

または、

$ find `/usr/bin/perl -e 'print join(" ", @INC)'` -type f -name "*.pm" | grep Jcode