[Catalyst] Sort something in the stash

Krzysztof Krzyżaniak eloy at pawnhearts.eu.org
Wed Jun 7 15:32:41 CEST 2006


"Ryan" <god at detz.net> writes:

> This probably already exists in perl but it's something I've come upon a
> few times and I was seeing if there was a way to do it.
>
> I use Template to view the pages so for data I store it in a array of
> hashes so I can loop and grab the data.
>
> $c->stash->{results}->[0]->{id} = 1;
> $c->stash->{results}->[0]->{name} = 'test';
>
> Something like that...and I want to be able to sort on say 'name' in that
> structure. Anyone know an easy way to sort by an array of hashes on a key?

erm, perldoc -f sort? 

#!/usr/bin/perl
use strict;
use Data::Dumper;

my @s = (
    {"name" => "aaba", "id" => 2},
    {"name" => "caba", "id" => 0},
    {"name" => "baba", "id" => 1}
);

my @a = sort {$a->{'name'} cmp $b->{'name'}} @s;
my @b = sort {$a->{'id'} <=> $b->{'id'}} @s;
print Dumper \@a;
print Dumper \@b;

result:

$VAR1 = [
          {
            'name' => 'aaba',
            'id' => 2
          },
          {
            'name' => 'baba',
            'id' => 1
          },
          {
            'name' => 'caba',
            'id' => 0
          }
        ];
$VAR1 = [
          {
            'name' => 'caba',
            'id' => 0
          },
          {
            'name' => 'baba',
            'id' => 1
          },
          {
            'name' => 'aaba',
            'id' => 2
          }
        ];


... or maybe I missing some point?

  eloy
-- 
-------e-l-o-y----------------------------e-l-o-y- at -k-o-f-e-i-n-a-.-n-e-t------

       jak to dobrze, że są oceany - bez nich byłoby jeszcze smutniej



More information about the Catalyst mailing list