Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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

In reply to Re: array pre-allocation trick by BrowserUk
in thread array pre-allocation trick by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (2)
As of 2024-04-20 05:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found