in reply to Re: Template, sorting an array with only one member
in thread Template, sorting an array with only one member

I've put together a test script demonstrating how my data model works. Please tell me this fails for you, or I might go insane. Bonus points if you can tell me how to fix it.

#!/usr/bin/perl use strict; use warnings; use Template; my $container = Container->new(); $container->add( Object->new( name => 'foo', value => 10, usefulness => 0 ) ); $container->add( Object->new( name => 'bar', value => 20, meaning => 42 ) ); my $vars = { 'container' => $container }; my $template = <<EOT; container=[% container %] all: [% FOREACH element IN container.all.sort('name') %] [% element %] name is [% element.name %] [% END %] one: [% FOREACH element IN container.one(10).sort('name') %] [% element %] name is [% element.name %] [% END %] EOT my $tt = Template->new(); $tt->process(\$template, $vars); package Object; sub new { my $class = shift; my $self = {@_}; return bless($self, $class); } package Container; sub new { my $class = shift; my $self = {@_}; return bless($self, $class); } sub add { my $self = shift; my $new = shift; push @{$self->{'objects'}}, $new; } sub all { my $self = shift; return @{$self->{'objects'}}; } sub one { my $self = shift; my $filter = shift; return grep { $_->{'value'} == $filter } @{$self->{'objects'}}; }
-- FloydATC

Time flies when you don't know what you're doing

Replies are listed 'Best First'.
Re^3: Template, sorting an array with only one member
by Mr. Muskrat (Canon) on Oct 20, 2014 at 18:10 UTC

    Container's one method is returning a single Object object instead of an array reference with a single Object object inside.

    The fix is quite simple:

    sub one { my $self = shift; my $filter = shift; return [ grep { $_->{'value'} == $filter } @{$self->{'objects'}} ]; }

    Output:

    container=Container=HASH(0x1cc2e10)
    all:
    
    Object=HASH(0x1cdf6b0) name is foo
    
    Object=HASH(0x1cdf788) name is bar
    
    one:
    
    Object=HASH(0x1cdf6b0) name is foo
    
    

Re^3: Template, sorting an array with only one member
by ysth (Canon) on Oct 20, 2014 at 18:16 UTC
    Have one/all return arrayrefs, not lists?
    sub all { my $self = shift; return $self->{'objects'}; } sub one { my $self = shift; my $filter = shift; return [ grep { $_->{'value'} == $filter } @{$self->{'objects'}} ]; }

      You're absolutely right, both of you... Damnit. Well, at least I'll be able to sleep tonight :-)

      -- FloydATC

      Time flies when you don't know what you're doing