だるろぐ

だるいぶろぐです

my $s = -hoge;

また一つ知った。

use strict;
use warnings;
sub say {print @_, "\n"}

my $s;
$s= -hoge;
say $s;
$s= -+hoge;
say $s;
$s= -+-hoge;
say $s;
$s= -+-+hoge;
say $s;
% perl t.pl
-hoge
-hoge
+hoge
+hoge

ハイフン付きの裸の文字列。しかも+を付けると変わる。何でクォートしないのに通るのか。
use Test::Base -Base; のように、useの第二引数に取れる事は知っていたが、変数宣言にも使えるのは知らなかった。そもそもuseの場合も何で使えてるのか分かってない。
全然分からなかったので某黒帯柔道家に質問。またか。

% perldoc perlop

  Symbolic Unary Operators

    Unary "!" performs logical negation, i.e., "not". See also "not" for a
    lower precedence version of this.

    Unary "-" performs arithmetic negation if the operand is numeric. If the
    operand is an identifier, a string consisting of a minus sign
    concatenated with the identifier is returned. Otherwise, if the string
    starts with a plus or minus, a string starting with the opposite sign is
    returned. One effect of these rules is that -bareword is equivalent to
    the string "-bareword". If, however, the string begins with a
    non-alphabetic character (exluding "+" or "-"), Perl will attempt to
    convert the string to a numeric and the arithmetic negation is
    performed. If the string cannot be cleanly converted to a numeric, Perl
    will give the warning Argument "the string" isn't numeric in negation
    (-) at ....

和訳。
perlop - Perl の演算子と優先順位 - perldoc.jp

単項演算子の "-" は被演算子が数値であれば、算術否定を行ないます。被演算子が識別子ならば、マイナス記号にその識別子をつなげた文字列が返されます。これ以外で被演算子の最初の文字がプラスかマイナスのときには、その記号を逆のものに置き換えた文字列を返します。この規則の結果、-bareword が文字列 "-bareword" に等価となります。しかし、文字列が英字以外("+" と "-" を除く)で始まっていると、 Perl は文字列を数値に変換しようとし、それから算術否定が実行されます。もし文字列が明確に数値に変換できない場合、Perl は Argument "the string" isn't numeric in negation (-) at ... という警告を出します。

だそうな。


こんな使い方をしているモジュールは Test::Base と Util::Any しか知らない。ので、使っている人に訊いてみた。まあ、毎度質問してるのだけど。
これ、クォートしなくてもいい以外にメリットあるんだろうか?

あと質問の際に、CGI.pmでも使っていると教えてもらった。本人はそれで知ったそうな。


というわけで毎度毎度ありがとうございました。

あとがき的な

俺がperlでどーしても分からない事に出会ったときの行動パターン。

  1. ひたすらperldoc
  2. 助けてgoogle

以上を3、4ループしたり、3、40分経っても分からず、かつ心が折れたら件の人に泣きついている。ほんと毎度お世話になりまくってます。


んで今回、俺のperldocの歩き方は

perldoc perl
perldoc perldoc
perldoc style
perldoc perlfaq
perldoc perlfaq[1-9]
perldoc perlsyn
perldoc perlop
perldoc perlvar

あたりを hyphen でgrepしてた。見てのとおり正解に近づいているのに。
件の人に訊いたとき、perldocのどこにあるかまでは知らなかったのだがあっさりと見つけられてた。
探し方は - でperldocをgrepしてったと。
はい俺残念。手元に素敵な辞書があっても引き方が悪くて使いこなせてません。


あと、DBICでもsearchのwhere句に -and とか -or とか使えるんだけど、あーあれはand/orがそもそもperl予約語だからかーとか今更気付かされた。こいつは- 付いてる意味は特に無かった。