5分で終る Perl 入門
Menu Menu
Perl ぐらい入ってるよね?
/usr/bin/perl にあるはず。Windows だと入ってないかも。
http://www.activestate.com/activeperl
ターミナルから使うのだが… Command Prompt よりは、他のものが良いかも。zsh とか。
Perlの使い方
一通り「動かしてみる」。Perl は怪しいと思ったら動かしてみること。大抵の場合、「望むとおり」に動くが、それはいつも同じように動くのとは違う。
デバッガ
> perl -de 0
Loading DB routines from perl5db.pl version 1.3
Editor support available.
Enter h or `h h' for help, or `man perldebug' for more help.
main::(-e:1): 0
DB<1>
簡単な計算
DB<1> p 1+1
2
DB<2> p hex(10)
16
DB<3> printf("%x",1000000)
f4240
DB<4>
変数への代入
DB<4> $x = 3
DB<5> p $x
3
DB<6> $x = "Shinji"
DB<7> p $x
Shinji
DB<8>
値が一つの変数をスカラと呼びます。文字でも数字でも良い。
変数を使った計算
DB<8> p "$x is a man."
Shinji is a man.
DB<9> $y = 100
DB<10> p "$y yen"
100 yen
明示的に文字列結合したければ . を使う。
DB<11> p $x." ".$y
Shinji 100
文字列は数字に変換される
DB<12> p $y+10
110
DB<13> p $x+10
10
DB<14> $z = "1234"
DB<15> p $z/3
411.333333333333
配列
DB<1> $x[0] = 3
DB<2> $x[10] = "test"
DB<3> p "@x"
連想配列
DB<4> $x{kono} = "shinji"
DB<5> $x{tamaki} = "shoshi"
DB<6> p $x{kono}
shinji
DB<7> p keys %kono
DB<8> p keys %x
tamakikono
DB<9> foreach my $key (%x) { print $x{$key}; }
shoshishinji
変数のスコープ
必ず my を付ける
my を付ける方が少し速い (理由は不明)
サブルーチン
sub f1 {
my ($arg1,$arg2,$arg3) = @_;
print "$arg1,$arg2,$arg3\n";
}
&f1(1,2,3);
Perl の標準的な構文設定
#!/usr/bin/perl -w
use strict;
use warnings;
までは入れておこう。
正規表現
/kono/
/[a-zA-Z]*/
/[a-z]*/
/^[^a-z]/
default では $_ に match 。$_ を Perl では良く使う。
$x に対して操作したい場合には、
$x = "test";
$x =~ /t/;
置換は、
$x =~ s/aaa/bbb/;
$x =~ s/aaa/bbb/g; # 全部置き換える
while 文
while(<>) {
}
print $i while ($i++ < 5)
if 文
if (/pattern/) {
}
next if (/pattern/); # 次のループへ
last if (/pattern/); # ループを抜ける
$i++ if (/pattern/);
便利な関数
山程ある。必ず、Perl debugger で試してみること。
split
入力を配列に分解する。
DB<4> $_ = "test1 test2 test3"
DB<5> @cols = split
DB<6> p $cols[1]
test2
パターンを使った分解
DB<7> @cols = split(/\t/,"test1\ttest2\ttset3")
DB<8> p $cols[2]
tset3
perldoc -f split とかで調べよう。
ファイルの入出力
#!/usr/bin/perl
while(<>) {
if(/hoge/) {
print;
}
}
これで、ほとんどの用が足りるはず。
print は、print $_; の省略。入力行が $_ に入っている。
open(OUT,">out.txt");
$file = "test.txt";
open(IN,"<$file") or die("$! $file\n");
while(<IN>) {
print OUT $_;
}
この die は付けないと後悔するので必ず付ける。
open(OUT,">out.txt");
は、
open(my $fh, '<', "input.txt") or die $!; print $fh $_;とするのが現代的。
print OUT の後にはコンマは付けない。
Module の使い方
use Getopt::Std;
getopts('ndh');
CPAN の使い方
cpan install DBD-SQLite
ActivePerl だと ppm の方が良いらしい。
ppm install DBD-SQLite
Windows で Proxy が必要な時には、
set HTTP_PROXY=http://proxyname:port
マニュアル
perldoc perl
暇な時に、
perlintro Perl introduction for beginners
個別の関数を知りたい時、
perldoc -f sprintf
モジュールを知りたい時、
perldoc Time::HiRes英語で読む。日本語ドキュメントが追い付くことは絶対にないので。本はさらに遅い。
時代遅れにならないように注意する。
scalar と array
Perl の関数は単一の値(scalar)を要求する場合と、リスト(array)を要求する場合があり、動作が異なる場合。
my $a = <IN>; # 1行読み込まれる
my @a = <IN>; # 全部読み込まれる
Perl のオブジェクト
bless で module と参照をつなげる。