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

Hi, I'm trying to initialise a hash with start values / construct but can't seem to improve on the following. I feel I'm creating a load of temporary variables for no good reason, suggestions?:

for ('02'..'03') { my $month = $_; $bucket{$month} = (); for ('00' .. $mons{$month}) { my $day = $_; $bucket{$month}{$day} = (); for ('00' .. '24') { my $hour = $_; $bucket{$month}{$day}{$hour} = (); for ('00' .. '59') { my $minute = $_; $bucket{$month}{$day}{$hour}{$minute} = [0,0]; } } } }

Replies are listed 'Best First'.
Re: hash initialisation
by davorg (Chancellor) on Mar 26, 2001 at 19:14 UTC

    Yes, you are :)

    There are a couple of optimisations you can make here. Firstly, you have may constructs like:

    for ('something' .. 'something else') { my $var = $_;

    where you can use:

    for my $var ('something' .. 'something else') {

    Secondly, and more importantly, at each level you initialise the elements to empty lists, with code like:

    $bucket{$x}{$y} = ();

    But on the next level down ,you overwrite it with an reference to a hash. The initial assignment is unnecessary.

    In fact, you can simply the whole thing to:

    for my $month ('02'..'03') { for my $day ('00' .. $mons{$month}) { for my $hour ('00' .. '24') { for my $minute ('00' .. '59') { $bucket{$month}{$day}{$hour}{$minute} = [0,0]; } } } }
    --
    <http://www.dave.org.uk>

    "Perl makes the fun jobs fun
    and the boring jobs bearable" - me

      If performance matters then temporaries may be your friend. For instance the following should run several times faster than your code:
      foreach my $month ('02'..'03') { my $m_bucket = $bucket{$month} = {}; foreach my $day ('00' .. $mons{$month}) { my $d_bucket = $m_bucket->{$day} = {}; foreach my $hour ('00'..'23') { my $h_bucket = $d_bucket->{$hour} = {}; foreach my $minute ('00'..'59') { $h_bucket->{$minute} = [0,0]; } } } }
      (A useful trick I have put to good use in the past.)
      doh!! :),
      Plus I just realised that hours in the day don't go from 00 to 24,
      well not unless you've had a few too many beers