I am wondering about how I can do in Perl what I commonly do in lisp:
(defvar *verbose-level* 0)
(defun my-function (... &key ((:verbose-level *verbose-level*) *verbose-level*) ...) ...)
this means that my-function
is run at the current level of verbosity, but I can pass it a different level which will affect all its calls too:
(defun f1 (&key ((:verbose-level *verbose-level*) *verbose-level*))
(format t "~S: ~S=~S~%" 'f1 '*verbose-level* *verbose-level*)
(f2 :verbose-level 1)
(format t "~S: ~S=~S~%" 'f1 '*verbose-level* *verbose-level*)
(f2 :verbose-level (1+ *verbose-level*))
(format t "~S: ~S=~S~%" 'f1 '*verbose-level* *verbose-level*))
(defun f2 (&key ((:verbose-level *verbose-level*) *verbose-level*))
(format t "~S: ~S=~S~%" 'f2 '*verbose-level* *verbose-level*))
[17]> (f1)
F1: *VERBOSE-LEVEL*=0
F2: *VERBOSE-LEVEL*=1
F1: *VERBOSE-LEVEL*=0
F2: *VERBOSE-LEVEL*=1
F1: *VERBOSE-LEVEL*=0
NIL
[18]> (f1 :verbose-level 4)
F1: *VERBOSE-LEVEL*=4
F2: *VERBOSE-LEVEL*=1
F1: *VERBOSE-LEVEL*=4
F2: *VERBOSE-LEVEL*=5
F1: *VERBOSE-LEVEL*=4
(note that the variable bindings are restored on exit - even abnormal - from functions).
How can I do something like that in Perl?
E.g., in misc.pm
, I have our $verbose=0;
.
How do I write a function which would bind $verbose
to a value of its argument and restore its value on return?