A nice way of keeping things together when pre-allocating arrays is to use the fact that my is a function and do the declaration and preallocation in the same statement like this.
Update: I swear it worked 10 minutes ago when I tested it.But I tried it in a perl shell, and first time I tried it I did
$#{\@a} = 50; print scalar @a; which printed 51. Great!
Then I thought "Ah! Should have used my", so I recalled the line, and added the my, and again it printed 51.........so I posted.
My little perl shell has its uses, but ......
Thanks to sauoq who brought me to book.
$#{\my @array} = 100;
</Update>
The idea can also be extended to pre-allocating hash buckets like this
keys my %hash = 2**8;
Though this is tougher to verify as if you immediatly evaluate the hash in a scalar context print scalar %hash; you get 0, which is disconcerting. However, if you then add one key to the hash %hash= (a=>1); print scalar %hash; you get 1/256 showing that it did work but simply fails to report the fact until it has at least one key.
In reply to Re: array pre-allocation trick
by BrowserUk
in thread array pre-allocation trick
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |