Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

無名配列へのリファレンスを作るときの話

配列へのリファレンスを扱おうとして

Not an ARRAY reference at ./hoge.pl line 70, <> line 4016.

みたいに言われた。 hoge.pl の 70 行目は

foreach (sort { $a->[4] <=> $b->[4] } @hogerefar) {

(@hogerefar の要素は配列へのリファレンス)となっていて、間違っているようには見えない。


エラーの原因は @hogerefar へリファレンスを push するときに

push(@analyzedref, \($normalized_ref, $is_search, $readable_ref, $org_ref, $ref_count));

としていたこと。無名の配列へのリファレンスを push しようとしているならこれは誤りで、

push(@analyzedref, (\$normalized_ref, \$is_search, \$readable_ref, \$org_ref, \$ref_count));

(リファレンスが入った無名配列を push)と同義になってしまう。正しくは以下:

push(@analyzedref, [$normalized_ref, $is_search, $readable_ref, $org_ref, $ref_count]);

ブラケットを使えば、無名の配列へのリファレンスを作成することができる。


参考: http://www.kt.rim.or.jp/~kbk/perl5.005/perlref.html