Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Making an array of predifined length with default values

by johnvandam (Acolyte)
on Mar 04, 2009 at 11:43 UTC ( [id://748083]=perlquestion: print w/replies, xml ) Need Help??

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

Call me silly, but I'm frustrated a bit with the following:
I would like to make an array of say, a thousand elements each filled with 0. What would be the fastest, cleanest way of doing this?

For a string we can replicate a substring:

$string = 0 x 1000;

This will give me a string of a thousand 0's.

For making an array in similar fashion this is the shortest method I can think of:

$_ = 0 foreach (@array = (1..1000));

I could also use split:

@array = split //, 0 x 1000;

But this I think will be more costly because you invoke the regexp engine, I guess.

So my question is: Is there some infinitely better, more perly method of making an array of predefined length with identical values? (Comparable maybe to the more satisfying way of doing something similar for a string?)

Thanks for all the help!

Replies are listed 'Best First'.
Re: Making an array of predifined length with default values
by almut (Canon) on Mar 04, 2009 at 11:53 UTC
    my @array = (0) x 1000;

    Even works with lists of arbitrary length, such as my @array = (1, 2, 3) x 100;  (which creates 300 elements).

    (but memory-wise, it's not better than iteratively filling the elements, maybe even with predeclaring some initial max size with $#array = 1000; to avoid successive automatic resizing...)

      Just a very minor nit: the statement  $#array = 1000; sets the maximum array index to 1000 and so predeclares an array with 1001 elements (assuming $[ == 0; see perlvar).
      Thanks, this works perfectly! I though it only worked for strings. Thanks again
Re: Making an array of predifined length with default values
by derby (Abbot) on Mar 04, 2009 at 11:54 UTC

    The fastest way to pre-extend an array by assigning a value to it's length:

    my @array; $#array = 10000;
    Now for pre-filling ... don't know. I would Benchmark the approaches you outline (and for grins, I would benchmark pre-extending too).

    -derby

    Update: Doh!. Thanks almut, now I know.

Re: Making an array of predifined length with default values
by clueless newbie (Curate) on Mar 04, 2009 at 11:59 UTC
    perhaps @a=(0) x 1000;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (5)
As of 2024-04-23 07:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found