in reply to Grouping Objects by Attribute

some untested pseudo-code ;) to get you started...

my %monks_by_level; for my $monk ( @array_of_monks ) { my $level = $monk->level(); # or ->{level} or whatever... push @{ $monks_by_level{$level} }, $monk; } for my $level ( keys %monks_by_level ) { print "doing $level...\"; callToPrayer( $monks_by_level{$level} ); } sub callToPrayer { my ($monks) = @_; for my $monk ( @$monks ) { print "$monk->name() here!\n"; } }
--
edan

Replies are listed 'Best First'.
Re^2: Grouping Objects by Attribute
by loris (Hermit) on Nov 01, 2004 at 09:47 UTC
    Thanks, edan, that did the trick.

    However, I don't quite get the bit

    @{ $monks_by_level{$level} }

    I understand this to mean that the $monks_by_level{$level} is the value of the hash for the key $level and that the @{ ... } around it automagically makes this value an array. Is this right?

    loris

      You're right, you just need a bit of terminology thrown in there. $monks_by_level{$level} is an array reference (see perlref for details) and @{ } is how we dereference an array reference, so that we can use it as an array. You could also dereference individual scalars in the array using syntax such as $monks_by_level{$level}[0].

      --
      edan