fork download
  1. #!/usr/bin/env bash
  2. # dynamic_scope_demo.sh
  3. # Mirrors the C-like program from the hand-out under dynamic scoping.
  4.  
  5. ############################
  6. # global variables (start all at 0)
  7. ############################
  8. a=0
  9. b=0
  10. c=0
  11. d=0
  12.  
  13. ############################
  14. # g1, g2, g3
  15. ############################
  16. g1 () { # g1(int b ; int c)
  17. local b=$1 c=$2
  18. printf '%d %d %d %d\n' "$a" "$b" "$c" "${d:-0}"
  19. }
  20.  
  21.  
  22. g2 () { # signature: g2(int a ; int c)
  23. local a=$1 c=$2
  24. g1 "$a" "$c"
  25. }
  26.  
  27. g3 () { # signature: g3(int c ; int a)
  28. local c=$1 a=$2
  29.  
  30. local b=3
  31. g1 "$a" "$b" # first print-line
  32.  
  33. # -------- inner block --------
  34. local c=8 # shadows the parameter c
  35. local d=4
  36. g2 "$a" "$b" # second print-line
  37. unset d # end of inner block – restore older ‘d’
  38. # -------- end block ---------
  39.  
  40. g1 "$a" "$b" # third print-line
  41. echo "$b" # “return” value
  42. }
  43.  
  44. ############################
  45. # main
  46. ############################
  47. main () {
  48. local a=4
  49. local b=5
  50. a=$(g3 "$b" "$c") # c is still the global 0
  51. g3 "$b" "$a"
  52. }
  53.  
  54. main
  55.  
Success #stdin #stdout #stderr 0.01s 5312KB
stdin
Standard input is empty
stdout
0 0 3 0
0 0 3 4
0 0 3 0
3
stderr
prog.pl: line 18: printf: 0 0 3 0
0 0 3 4
0 0 3 0
3: invalid number
prog.pl: line 18: printf: 0 0 3 0
0 0 3 4
0 0 3 0
3: invalid number
prog.pl: line 18: printf: 0 0 3 0
0 0 3 4
0 0 3 0
3: invalid number
prog.pl: line 18: printf: 0 0 3 0
0 0 3 4
0 0 3 0
3: invalid number
prog.pl: line 18: printf: 0 0 3 0
0 0 3 4
0 0 3 0
3: invalid number
prog.pl: line 18: printf: 0 0 3 0
0 0 3 4
0 0 3 0
3: invalid number