Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I`m trying to access an array of structs. The ``for my $struct (@structs)'' way works, but I don`t know how to directly access a struct in the array. Saying sth. like ``$structs[0]->name'' for instance gives an error ("Can't call method "name" on unblessed reference"). Is there a way to access it directly? If so please tell me, I`ll name my first child after you if you do :) thanks in advance Joern

Replies are listed 'Best First'.
Re: Accessing an array of structs
by kyle (Abbot) on Apr 04, 2007 at 13:40 UTC

    I think you want $structs[0]->{name} (the $structs[0]->name looks to Perl like $structs[0]->name(), that is, a method call on the first element of @structs).

Re: Accessing an array of structs
by ferreira (Chaplain) on Apr 04, 2007 at 13:43 UTC

    What are those "structs"? Real C structs passed by some C binding or just hash refs? In the first case, the issue is more complicated and may involve unpack and a few tweaks until the right data is visible to Perl (not necessarily in a portable way). In the second change, replace $structs[0]->name with $structs[0]->{name} and you'll be fine.