| 1 | #!/usr/bin/env bash
|
| 2 | #
|
| 3 | # Usage:
|
| 4 | # ysh/testdata/inline-function-calls.sh <function name>
|
| 5 |
|
| 6 | shopt -s ysh:upgrade
|
| 7 |
|
| 8 | source $LIB_YSH/list.ysh
|
| 9 |
|
| 10 | simple-demo() {
|
| 11 | var myarray = %(spam eggs ham)
|
| 12 |
|
| 13 | echo '+ Call in expression context:'
|
| 14 | var length = len(myarray)
|
| 15 | echo $length
|
| 16 | echo
|
| 17 |
|
| 18 | echo '+ Inline call that coerces to string:'
|
| 19 | write -- $[len(myarray)] $[len("abc")] ''
|
| 20 | echo
|
| 21 |
|
| 22 | echo '+ Inline calls can be part of a word:'
|
| 23 | write -- --length=$[len(myarray)] $[len("abc")]$[len("xyz")]
|
| 24 | echo
|
| 25 |
|
| 26 | echo "+ Caveat: can't double quote. It would break programs."
|
| 27 | echo " Should we add an option 'shopt -s parse_dparen'?"
|
| 28 | echo
|
| 29 |
|
| 30 | # NOTE: Oil's echo builtin takes --, and requires it here
|
| 31 | write -- "--length=$[len(myarray)]"
|
| 32 | echo
|
| 33 |
|
| 34 | echo '+ Just as you can splice @myarray'
|
| 35 | write -- @myarray
|
| 36 | echo
|
| 37 |
|
| 38 | var mydict = { 'hello': 0, 'world': 1 }
|
| 39 |
|
| 40 | echo '+ You can also splice the result of a function returning a sequence:'
|
| 41 | echo ' Notes:'
|
| 42 | echo ' - the Dict->reverse() method is from Python.'
|
| 43 | echo
|
| 44 | write -- @[mydict->keys()]
|
| 45 | echo
|
| 46 |
|
| 47 | # But this is a syntax error
|
| 48 | #echo @sorted(myarray)@invalid
|
| 49 | }
|
| 50 |
|
| 51 | split-join-demo() {
|
| 52 | var parts = %(aaa BB c)
|
| 53 | write -- 'Parts:' @parts
|
| 54 | echo
|
| 55 |
|
| 56 | write 'join(parts):' $[join(parts)]
|
| 57 | echo
|
| 58 |
|
| 59 | echo '+ Another way of doing it, without creating another variable:'
|
| 60 | write --sep '' -- @parts
|
| 61 | echo
|
| 62 |
|
| 63 | var j = join(parts, ":")
|
| 64 | #var a = split(j)
|
| 65 | #repr j a
|
| 66 |
|
| 67 | write --sep '' "j => " $j
|
| 68 | write --sep '' 'When IFS is the default, split(j) => '
|
| 69 | write @[split(j)]
|
| 70 | echo
|
| 71 |
|
| 72 | # NOTE: Can't use setvar IFS = ':' here because of static check
|
| 73 | # declare or declare -g makes sense
|
| 74 | declare IFS=':'
|
| 75 | echo 'When IFS is :, split(j) => '
|
| 76 | write @[split(j)]
|
| 77 | echo
|
| 78 |
|
| 79 | unset IFS
|
| 80 |
|
| 81 | echo '+ Since there is no word splitting of unquoted $(ls), here is an idiom:'
|
| 82 | write @[split( $(write bin/ lib/ | grep b) )]
|
| 83 | }
|
| 84 |
|
| 85 | types-demo() {
|
| 86 | echo 'TODO: bool, int, etc.'
|
| 87 | }
|
| 88 |
|
| 89 | all() {
|
| 90 | simple-demo
|
| 91 | split-join-demo
|
| 92 | }
|
| 93 |
|
| 94 | "$@"
|