Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: array pre-allocation trick

by BrowserUk (Patriarch)
on Oct 31, 2002 at 02:25 UTC ( [id://209313]=note: print w/replies, xml ) Need Help??


in reply to array pre-allocation trick

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.


Nah! Your thinking of Simon Templar, originally played by Roger Moore and later by Ian Ogilvy

Replies are listed 'Best First'.
Re: Re: array pre-allocation trick
by sauoq (Abbot) on Oct 31, 2002 at 02:43 UTC

    Are you sure that trick with array pre-allocating does what you think it does? My short experiment suggests otherwise:

    $ perl -le '$#{\my @array}=100;print scalar @array' 0 $ perl -le 'my @array;$#array=100;print scalar @array' 101

    Using strict clears things up...

    $ perl -le 'use strict;$#{\my @array}=100;print scalar @array' Global symbol "@array" requires explicit package name at -e line 1. Execution of -e aborted due to compilation errors.

    The my lexically scopes @array to the block which you then use as a reference.

    -sauoq
    "My two cents aren't worth a dime.";
    

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://209313]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (1)
As of 2024-04-25 03:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found