だるろぐ

2010-04-28

+shift とか -hoge とか

| 00:07 | +shift とか -hoge とかを含むブックマーク

perlで + とか - の、プラスとかマイナスの記号は加算・減算以外にも使えるんだけど

+{}は無名ハッシュの宣言っていうソースはperldoc -f mapにあった - だるろぐ跡地

my $s = -hoge; - だるろぐ

また知った。

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

my %h = (
    hoge   => '_hoge',
    shift  => '_shift',
    -shift => '_shift_minus',
);

sub f1 {
    say $h{shift}
}

sub f2 {
    say $h{+shift}
}

sub f3 {
    say $h{-shift}
}

f1("hoge");
f2("hoge");
f3("hoge");
% perl kigou.pl
_shift
_hoge
_shift_minus

まあそういうことである。そもそも変数で受け取れと。


そしてどこに載っているかというと

% perldoc perlop

-snip-

    Unary "+" has no effect whatsoever, even on strings. It is useful
    syntactically for separating a function name from a parenthesized
    expression that would otherwise be interpreted as the complete list of
    function arguments. 

はい訳。

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

単項演算子の "+" は、たとえ文字列に対して用いられた場合にも、何もしません。関数名に続けて括弧付きの式を書く場合に、関数引数リストと解釈されないようにするために用いることができます。

裸の文字列が許される場所において、文字列と同名の関数がある場合に、文字列なのか関数なのかを明示的に指定するってことか。

まぁshiftなんて関数定義する事は無いだろうけど。


今回は黒帯柔道家に訊かずに済みました。つーても前回と同じ場所で見覚えあったからですが。

トラックバック - http://d.hatena.ne.jp/hirafoo/20100428

事務用品 名刺 デザイン