]> granicus.if.org Git - jq/commitdiff
Add general `?` operator
authorNicolas Williams <nico@cryptonector.com>
Sun, 6 Jul 2014 05:11:55 +0000 (00:11 -0500)
committerNicolas Williams <nico@cryptonector.com>
Sun, 6 Jul 2014 06:29:43 +0000 (01:29 -0500)
docs/content/3.manual/manual.yml
parser.y
tests/all.test

index 4d3ac45f3abaaf09003a2673415e235a711b4bc7..973e8d855c7e4dd6caaa4a847f5dcc7739fc29b6 100644 (file)
@@ -1584,6 +1584,16 @@ sections:
             input: 'true'
             output: ['"some exception"']
 
+      - title: `?` operator
+        body: |
+
+          The `?` operator, used as `EXP?`, is shorthand for `try EXP`.
+
+        examples:
+          - program: '[.[]|(.a)?]'
+            input: '[{}, true, {"a":1}'
+            output: ['[null, 1]']
+
   - title: Advanced features
     body: |
       Variables are an absolute necessity in most programming languages, but
index bfd09d35943b77572b79a7df3bc3ee546986ae33..eb63381a43d0bc988729ab4a88b557d3a683d2a8 100644 (file)
--- a/parser.y
+++ b/parser.y
@@ -255,6 +255,10 @@ Term "as" '$' IDENT '|' Exp {
   $$ = $2;
 } |
 
+Exp '?' {
+  $$ = gen_try($1, gen_op_simple(BACKTRACK));
+} |
+
 
 Exp '=' Exp {
   $$ = gen_call("_assign", BLOCK(gen_lambda($1), gen_lambda($3)));
index f5c7bd68e1e2823cab548e9cc4aca583ccebf3c9..4bd15cee586f4035c34bf70513fcea9c02f4b8c1 100644 (file)
@@ -670,6 +670,14 @@ def inc(x): x |= .+1; inc(.[].a)
 [0,1,2,3]
 ["foo","Cannot index number with string \"a\"",3]
 
+[.[]|(.a, .a)?]
+[null,true,{"a":1}]
+[null,null,1,1]
+
+[[.[]|[.a,.a]]?]
+[null,true,{"a":1}]
+[]
+
 # string operations
 [.[]|startswith("foo")]
 ["fo", "foo", "barfoo", "foobar", "barfoob"]