A Perl trick that I always forget

Found this buried away in the back of my mind. Let’s say you want to create an array with 20 elements, set to the same initial value. You might do this:

my @array = ();
for(my $i = 0; $i <= 19; $i++) {
    $array&#91;$i&#93; = "0.00";
}
&#91;/sourcecode&#93;
Or you might recall the very useful <em>repetition operator</em>:

my @array = ("0.00") x 20

As they say, TMTOWTDI – but some ways are better than others.

4 thoughts on “A Perl trick that I always forget

  1. Jonathan Badger

    Since you know some Ruby, do you know that Ruby has this feature too? Of course, being object-oriented, it doesn’t need to use a special operator — the normal multiplication operator suffices…

    x = [0.00] * 20

    And of course this works with any object that responds to the multiplication operator —

    x = [7, 8] * 5
    x = “DNA” * 5
    etc.

  2. nsaunders Post author

    Yeah, I included a Ruby version in an edit of the post, then removed it again.

    My version was: arr = Array.new(20, “0.00”). Like yours too!

  3. Torsten Seemann

    Yes, I tend for forgot to use “x” with lists, but remember for strings…

    If you do need to use a loop to initialize, the postfix version of “for”, or “map”, are other concise options, and allow the indices to be something other than default 0.

    my @array;
    $array[$_] = 0.00 for (0..19);

    # or

    my @array = ( map { 0.00 } (0..19) );

Comments are closed.