in reply to Bloated code of loops and conditionals

Instead of array refs $data11a, $data11b, etc., make a hash whose keys are 11a, 11b, etc., and store the array refs in it. Then, instead of accessing $data11a->[ $n ] you'd access $data{ 11a }[ $n ]. Or use push to avoid explicit indices.

# my %goals; @goals{ qw( 11a 11b 22 33 ) } = (); my @flds = qw( id title summary ); if ($sqldata) { my %data; for my $d ( @$sqldata ) { my $g = $d->{ 'goal' }; # next unless exists $goals{ $g }; my %h; @h{ @flds } = @{ $d }{ @flds }; # hash slice assignment push @{ $data{ $g } }, \%h; } for my $g ( keys %data ) { $template ->param( "list$g" => $data{ $g } ); } }
If you really want to control the valid values for the "goal" parameters, then uncomment the two commented lines. This will cause any record with a "goal" not in this list to be ignored.

Update: Filled in the details. Fixed typo pointed out by bradcathey.

the lowliest monk

Replies are listed 'Best First'.
Re^2: Bloated code of loops and conditionals
by bradcathey (Prior) on Apr 23, 2005 at 00:07 UTC

    Thanks tlm (the artist formerly known as PP). It looks brilliant, but a bit beyond my experience. I have a couple of questions.

    - in the line:

    next unless exists $goal { $g }

    should $goal be goals with an 's'?

    - not sure what is going on with the 'hash slice assignment' line

    I'll plug this into my code, but I just wanted to understand it at the same time.


    —Brad
    "The important work of moving the world forward does not wait to be done by perfect men." George Eliot

      Regarding your first question, yes, that was a typo (now fixed).

      A hash slice is a way to access several values of a hash using a list of keys. For regular hashes, for example,

      @hash{ qw( foo bar baz ) } = ( 1, 2, 3 );
      has the same effect as
      $hash{ foo } = 1; $hash{ bar } = 2; $hash{ baz } = 3;
      You can use slices to copy several values from one hash to another. E.g.
      @keys = qw( foo bar baz ); @copy{ @keys } = @orig{ @keys };
      The last line copies three key-value pairs from %orig to %copy. In the code I posted earlier, the only difference is that the accessing of the RHS slice is done via a reference ($d) to a hash instead of a regular hash:
      @h{ @flds } = @{ $d }{ @flds }; # hash slice assignment
      Once you dereference a hash ref you can use it like any other hash.

      Slices are discussed in perldata, and using references in perlreftut and perlref.

      the lowliest monk