てきとうなメモ

本の感想とか技術メモとか

Hidden features of Perl

知らなかったものを抽出してみる.

sigil

For example, did you know that there can be a space after a sigil?

$ perl -wle 'my $x = 3; print $ x'
3

sigilの後の空白は無視される.$に限らず他のsigilでもそうなる

$ perl -wle 'my @ x = (1,2,3); print @ x'
123

空白以外の改行でもいいみたい

$ perl -wle 'my $
> x = 3; print $x'
3

q{},qq{}とかって文字で括ってもok

Update: Another nice one. Below the q{...} quoting constructs were mentioned, but did you know that you can use letters as delimiters?

$ perl -Mstrict  -wle 'print q bJet another perl hacker.b'
Jet another perl hacker.

Likewise you can write regexes

m xabcx
# same as m/abc/

読みにくさ抜群だがイイ

.gzファイルを<>から読めるようにする

Add support for compressed files:

s/.*\.gz$/zcat $_\|/ for @ARGV;

Now the <> feature will decompress any @ARGV files that end with .gz.

while (<>)
{
    print;
}

ちょっとコードを加えるだけでgzやbzをサポートできる.良さげ.

-nや-pのトリック

Based on the way the "-n" and "-p" switches are implemented in perl5, you can write a seemingly incorrect program including }{:
ls |perl -lne 'print $_; }{ print "$. Files"'
which is converted internally to this code:

LINE: while (defined($_ = <ARGV>)) {
    print $_; }{ print "$. Files";
}

普通にくっつけて実行していたのか.