List::MoreUtils::pairwise を使ってみる修行
二つの対応した文字列がある。もっと正確に言うと、それぞれをある記号で split したときの、各要素が対応している。対応した文字列要素のペアを基にごにょごにょして新しい要素を作り、それをリストにしたい。と、ややこしく書いているが、要するに List::MoreUtils::pairwise を「pairwise { mix($a, $b) } (split q{ }, $x), (split q{ }, $y)」として使いたい、ということ。
なんだけど、これは
[takeyuki@sunya ~]$ perl b.pl Type of arg 2 to List::MoreUtils::pairwise must be array (not split) at b.pl line 16, near ");" Type of arg 3 to List::MoreUtils::pairwise must be array (not split) at b.pl line 16, near ");" Execution of b.pl aborted due to compilation errors.
と怒られる。一旦配列変数に落とさないといけないらしい。で、
my @x = split q{ }, $x; my @y = split q{ }, $y; my @z = pairwise { mix($a, $b) } @x, @y;
とすると、今度は動くんだけど、
Name "main::a" used only once: possible typo at b.pl line 16. Name "main::b" used only once: possible typo at b.pl line 16.
なんて言われる。そりゃないよねえ、$a, $b って使わなきゃいけないし。
とりあえず警告を off にすればいいのかもしれない。面倒だけど。
use strict; use warnings; use List::MoreUtils qw/pairwise/; sub mix { my ($s1, $s2) = @_; my $u = "$s2($s1)"; return [length($s1), $u, lc($s2)]; } my $x = 'this is a test'; my $y = 'ThiS IS A TesT'; # my @z = pairwise { mix($a, $b) } (split q{ }, $x), (split q{ }, $y); my @x = split q{ }, $x; my @y = split q{ }, $y; my @z = pairwise { no warnings qw/once/; mix($a, $b) } @x, @y; foreach my $z (@z) { my ($len, $u, $v) = @{$z}; print join("\t", ($len, $u, $v)), "\n"; }
実行結果。
[takeyuki@sunya ~]$ perl b.pl 4 ThiS(this) this 2 IS(is) is 1 A(a) a 4 TesT(test) test