add as_hash to WrapArray
authorTony Cook <tony@develop-help.com>
Wed, 13 Aug 2014 04:37:57 +0000 (14:37 +1000)
committerTony Cook <tony@develop-help.com>
Wed, 13 Aug 2014 04:37:57 +0000 (14:37 +1000)
site/cgi-bin/modules/Squirrel/Template/Expr/WrapArray.pm
t/020-templater/040-original.t

index 5b1a2223229686a376749742247f5c8120e05cb6..3b3f9df36638afc1434caafe5e37be137e3a11ad 100644 (file)
@@ -4,7 +4,7 @@ use base qw(Squirrel::Template::Expr::WrapBase);
 use Scalar::Util ();
 use List::Util ();
 
-our $VERSION = "1.007";
+our $VERSION = "1.008";
 
 my $list_make_key = sub {
   my ($item, $field) = @_;
@@ -171,6 +171,17 @@ sub _do_set {
   return $args->[1];
 }
 
+sub _do_as_hash {
+  my ($self, $args) = @_;
+
+  @$args == 0
+    or die [ error => "list.as_hash takes no parameters" ];
+
+  my @extra = @{$self->[0]} % 2 ? ( undef ) : ();
+
+  return +{ @{$self->[0]}, @extra };
+}
+
 sub call {
   my ($self, $method, $args) = @_;
 
@@ -276,6 +287,14 @@ Return a new array with any contained arrays expanded one level.
 Set the specified I<index> in the array to I<value>.  Returns
 I<value>.
 
+=item as_hash
+
+Returns a hash formed as if the array was formed of key and value
+pairs.  If the number of elements is odd, the value for the odd key is
+C<undef>.
+
+ [ "a", 1, "b", 2 ].as_hash => { a:1, b:2 }
+
 =item is_list
 
 Test if this object is a list.  Always true for a list.
index d223a6d9fa564c54d8746405fe694630997df2eb..c1c620b38b70b1a64696d31fcc85894a9735852c 100644 (file)
@@ -1,7 +1,7 @@
 #!perl -w
 # Basic tests for Squirrel::Template
 use strict;
-use Test::More tests => 187;
+use Test::More tests => 188;
 use HTML::Entities;
 
 sub template_test($$$$;$$);
@@ -604,6 +604,7 @@ OUT
      [ '[ 1, 2 ].is_list', 1 ],
      [ '[ 1, 2 ].is_hash', 0 ],
      [ '[ 1 .. 5 ].shuffle.size', 5 ],
+     [ '([ "a", 1, "b", "2" ].as_hash)["a"]', 1 ],
 
      # WrapHash
      [ '{ "foo": 1 }.is_list', 0 ],