理系学生日記

おまえはいつまで学生気分なのか

qw/STRING/ では変数展開がなされない件

恥ずかしながら変数展開でハマったお話。

my $a = 'aaa';
print "$a\n";          # prints "aaa"
print qw($a), "\n";    # prints "$a"

ダブルクオテーションで囲むと当たり前だが変数は展開される。しかし、qw で囲んだ場合は変数展開がなされません。どの演算子(?)が変数展開をするかは、perldoc perlop にまとめられています。

           Customary  Generic        Meaning        Interpolates
               ''       q{}          Literal             no
               ""      qq{}          Literal             yes
               ``      qx{}          Command             yes*
                       qw{}         Word list            no
               //       m{}       Pattern match          yes*
                       qr{}          Pattern             yes*
                        s{}{}      Substitution          yes*
                       tr{}{}    Transliteration         no (but see below)
               <<EOF                 here-doc            yes*

               * unless the delimiter is ''.

まぁたしかに、qw/STRING/ が変数展開をしてしまうと、

my $a = "a b c";
print join "\n" => qw($a);

上記のように変数の中身にスペースを含んでいた場合に混乱してしまいそうですね。