tetsunosukeのnotebook

tetsunosukeのメモです

配列の添え字に負の数を使うと後ろから数える

「わな」にはまりました。

以前こちらの記事
http://d.hatena.ne.jp/kidd-number5/20060201/1138783615
で書いたプログラムで、負の値を入れると異常としてくれないという報告をid:ablaboさんから頂いていたわけなんですが、

Negative array subscripts now count from the end of the array.

    @a = (1, 2, 3, 4, 5);
    print "The third element of the array is $a[3] also expressed as $a[-2] \n";

    # perl4 prints: The third element of the array is 4 also expressed as
    # perl5 prints: The third element of the array is 4 also expressed as 4
こういうことだったのか! つまり defined($somearray[-1]) がtrueで返ってきてる。
if($_ = /\D/ and defined($person[$_-1])){
if($_ =~ /\d/ and $_-1 > 0 and defined($person[$_-1])){
とすべきか。 スジ的にはもう最初から1引いてから書くのが良いような気がする。