Last active
August 29, 2015 14:00
-
-
Save syohex/11164994 to your computer and use it in GitHub Desktop.
Patch for adding `first` and `last` method to builtin Array functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
diff --git a/lib/Text/Xslate/Manual/Builtin.pod b/lib/Text/Xslate/Manual/Builtin.pod | |
index 842c330..bdc51d3 100644 | |
--- a/lib/Text/Xslate/Manual/Builtin.pod | |
+++ b/lib/Text/Xslate/Manual/Builtin.pod | |
@@ -35,6 +35,14 @@ The namespace of ARRAY references is C<array>. | |
Returns true; | |
+=head3 C<$a.first()> | |
+ | |
+Returns the first element of I<$a>. | |
+ | |
+=head3 C<$a.last()> | |
+ | |
+Returns the last element of I<$a>. | |
+ | |
=head3 C<$a.size()> | |
Returns the number of elements of I<$a>. | |
diff --git a/src/xslate_methods.xs b/src/xslate_methods.xs | |
index 61e927c..fce4a0f 100644 | |
--- a/src/xslate_methods.xs | |
+++ b/src/xslate_methods.xs | |
@@ -83,6 +83,16 @@ tx_keys(pTHX_ SV* const hvref) { | |
/* SCALAR */ | |
/* ARRAY */ | |
+TXBM(array, first) { | |
+ SV **svp = av_fetch((AV*)SvRV(*MARK), 0, FALSE); | |
+ sv_setsv(retval, svp ? *svp : &PL_sv_undef); | |
+} | |
+ | |
+TXBM(array, last) { | |
+ AV* const av = (AV*)SvRV(*MARK); | |
+ SV **svp = av_fetch(av, av_len(av), FALSE); | |
+ sv_setsv(retval, svp ? *svp : &PL_sv_undef); | |
+} | |
TXBM(array, size) { | |
sv_setiv(retval, av_len((AV*)SvRV(*MARK)) + 1); | |
@@ -377,6 +387,8 @@ TXBM(hash, merge) { | |
} | |
static const tx_builtin_method_t tx_builtin_method[] = { | |
+ TXBM_SETUP(array, first, 0, 0), | |
+ TXBM_SETUP(array, last, 0, 0), | |
TXBM_SETUP(array, size, 0, 0), | |
TXBM_SETUP(array, join, 1, 1), | |
TXBM_SETUP(array, reverse, 0, 0), | |
diff --git a/t/050_builtins/002_autobox.t b/t/050_builtins/002_autobox.t | |
index 6cc76c8..25ca9e2 100644 | |
--- a/t/050_builtins/002_autobox.t | |
+++ b/t/050_builtins/002_autobox.t | |
@@ -60,6 +60,11 @@ my @set = ( | |
['<: $a.merge($a).join(",") :>', { a => [1, 2, 3] }, '1,2,3,1,2,3'], | |
['<: $a.merge([1, 2, 3]).join(",") :>', { a => [0] }, '0,1,2,3'], | |
+ ['<: $a.first() :>', { a => [1, 2, 3] }, '1', 'get first element'], | |
+ ['<: $a.first() :>', { a => [] }, '', 'first for empty array'], | |
+ ['<: $a.last() :>', { a => [1, 2, 3] }, '3', 'get last element'], | |
+ ['<: $a.last() :>', { a => [] }, '', 'last for empty array'], | |
+ | |
# hash | |
['<: $h.size() :>', { h => {} }, '0', 'for hash'], | |
['<: $h.size() :>', { h => {a => 1, b => 2, c => 3} }, '3'], |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment