Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
commands:builtin:declare [2013/04/14 14:50]
ormaaj [Nameref]
commands:builtin:declare [2013/04/14 22:11] (current)
ormaaj mirabilos' example for eventual portability section
Line 87: Line 87:
  
 <​code>​ <​code>​
-sum a set of arrays and assign the result indirectly, also printing each intermediary result (without portability workarounds)+Sum a set of arrays and assign the result indirectly, also printing each intermediary result (without portability workarounds) 
 +# sum name arrname [ arrname ... ]
 function sum { function sum {
     typeset -n _result=$1 _arr     typeset -n _result=$1 _arr
     typeset IFS=+     typeset IFS=+
     _result=0     _result=0
-    for _arr in "​${@:​2}";​ do+    for _arr in "​${@:​2}";​ do                        # Demonstrate the special property of "​for"​ on a nameref.
         (( _result += ${_arr[*]} ))         (( _result += ${_arr[*]} ))
-        printf '​%s ​is %d\n' "​${!_result}"​ "​$_result"​+        printf '​%s ​%d\n' "​${!_result}"​ "​$_result" ​# Demonstrate the special property of ${!ref} on a nameref.
     done     done
 } }
Line 100: Line 101:
 a=(1 2 3) b=(6 5 4) c=(2 4 6) a=(1 2 3) b=(6 5 4) c=(2 4 6)
 sum total a b c sum total a b c
-printf 'Final value of "​total"​ is: %d\n' "​$total"​'+printf 'Final value of "​total"​ is: %d\n' "​$total"​
 </​code>​ </​code>​
 +<div hide>
 +function sum {
 + typeset -n _result=$1
 + shift
 + typeset IFS=+ _arrx
 + _result=0
 + for _arrx in "​$@";​ do                        # Demonstrate the special property of "​for"​ on a nameref.
 + typeset -n _arr=$_arrx
 + (( _result += ${_arr[*]} ))
 + printf '%s = %d\n' "​${!_result}"​ "​$_result"​ # Demonstrate the special property of ${!ref} on a nameref.
 + done
 +}
 +
 +a=(1 2 3); b=(6 5 4); c=(2 4 6)
 +sum total a b c
 +printf 'Final value of "​total"​ is: %d\n' "​$total"​
 +</​div>​
  
 ''​typeset -n''​ is currently implemented in ksh93, mksh, and Bash 4.3. Bash and mksh's implementations are quite similar, but much different from ksh93'​s. See [[#​portability_considerations | Portability considerations]] for details. ksh93 namerefs are much more powerful than Bash'​s. ''​typeset -n''​ is currently implemented in ksh93, mksh, and Bash 4.3. Bash and mksh's implementations are quite similar, but much different from ksh93'​s. See [[#​portability_considerations | Portability considerations]] for details. ksh93 namerefs are much more powerful than Bash'​s.