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

I've got a program that uses an array of hashes to store start and stop times for various jobs. For readability and convenience, I'd like to use a reference in the loop that steps through the array -- something like this:
foreach my $job (@jobTimes) { $job{'startX'} = int(($job{'start'} - $dayStart) * $scaleConst); $job{'endX'} = int(($job{'end'} - $dayStart) * $scaleConst); $job{'start'} =~ s/^0+//; $job{'end'} =~ s/^0+//; }

Update: tedrek's suggestions worked when initializing the hash, but it's still erroring out when I try to work on it, as listed above. This is where I'd really like to avoid the $jobTimes$i{'foo'} construct.

Thanks,
Alex

Replies are listed 'Best First'.
Re: Reference to a single array item in an array of hashes?
by Ovid (Cardinal) on Apr 05, 2004 at 22:25 UTC

    Why use the extra variable?

    for my $i (0 .. $numTimes) { $jobTimes[$i] = { start => param("JobStart$i"), stop => param("JobStop$i"), }; }

    Cheers,
    Ovid

    New address of my CGI Course.

      Because then I end up with really ugly stuff like this:
      $jobTimes[$i]{'startX'} = int(($jobTimes[$i]{'start'} - $dayStart) * $ +scaleConst);
      When I would much rather have:
      $$job{'startX'} = int(($$job{'start'} - $dayStart) * $scaleConst);
Re: Reference to a single array item in an array of hashes?
by ccn (Vicar) on Apr 05, 2004 at 22:41 UTC
    you can use ref function to determine if an element is reference to hash or something else
Re: Reference to a single array item in an array of hashes?
by tedrek (Pilgrim) on Apr 05, 2004 at 22:48 UTC

    You can just use the built in aliasing of for loops, (I'm assuming this loop is initializing the array):

    #!/usr/bin/perl use strict; use warnings; my $numTimes = 2; my $i = 0; my @jobTimes = ('') x $numTimes; # Make the array big enough foreach my $job (@jobTimes) { $job = { start => param("JobStart$i"), }; $i++; }

    Update: made it compile and do what I mean.

    I tried to swear at perl and it compiled!
      Using that code gives an error "Global symbol "$job" requires explicit package name".

      I tried changing it to this:

      foreach my %job (@jobTimes)
      but it didn't like that either. Syntax error.

        I fixed a few things. But you shouldn't be getting that error unless you are trying to use $job outside of the loop.

        I tried to swear at perl and it compiled!