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

I can't replicate the problem:
#!/usr/bin/perl use warnings; use strict; use Template; my @arr = ( { name => 'Foo', value => 1 }, # { name => 'Bar', value => 2 }, ); 'Template'->new ->process(\'TEST: [% FOREACH element IN arr.sort("name") %] [% ele +ment.name %][% END %]', { arr => \@arr });

Output:

TEST: Foo
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^2: Template, sorting an array with only one member
by FloydATC (Deacon) on Oct 20, 2014 at 17:24 UTC

    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

      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
      
      

      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