Main Content

Out of memory during array extend - Perl

Archive - Originally posted on "The Horse's Mouth" - 2008-12-02 20:18:28 - Graham Ellis

Use a hash if you want a sparse list in Perl!

If you set up a list in Perl and don't fill all the members from zero up, that's OK but all the missing elements will actually use up some memory as they'll point to an "undef" value. So this happens:

Dorothy:ppcsrd08 grahamellis$ perl
$num[1223776336] = 0;
Out of memory during array extend at - line 2.
Dorothy:ppcsrd08 grahamellis$


That's attempting to create over 1 billion members of a list ... which would take an awful lot of memory.

You can, however, use a hash instead:

Dorothy:ppcsrd08 grahamellis$ perl
$num{1223776336} = 0;
Dorothy:ppcsrd08 grahamellis$


In a hash you name rather than number your elements ... but an element can be named with any scalar, thus allowing to produce a sparse collection - one in which you don't have to predefine a whole lot of keys in order to reach the one that you need.

Lists are written with square brackets - [ and ] - round each member, but members of a hash are written with curly braces - { and }. If you refer to the whole of a list, use the "@" character, but if you refer to the whole of a hash, use a "%".

You can learn a lot more about lists and hashes on our Perl Programming Course ... I'm teaching a private variant this week in Cambridge with some extra topics such as a little bit of socket programming ... see the next post ...