一千萬個為什麽

搜索

處理命令行args-left?

我有一個函數,我傳遞一個文件名後跟幾個整數參數。問題是我現在想要將我的代碼作為Unix腳本運行,使用 command-line-args-left 從命令行傳遞參數。當#1 調用process-args時,會創建一個包含所有值的列表。在#2 中,列表列表{例如。 ((1 2 3))}是在進入process-args時創建的。保持我的代碼通用的最佳方法是什麽,以便我可以在同一個函數中處理#1#2 兩種情況?

(defun process-args (filename &rest cols) ...) 
(process-args filename 1 2 3); #1
(process-args (car command-line-args-left) (cdr command-line-args-left)); #2

這是我正在測試的一些工作示例代碼:

#!/usr/bin/emacs --script

(defun process-args (filename &rest cols)
           (princ (concat "Script Name: " file "\n"))
       (princ (concat "File parameter: " filename "\n"))
       (princ "Other arg values: ")
       (princ cols)
       (princ "\nIs list: ")
       (princ (listp cols))
       (princ "\n----------\n")
       (while cols
         (princ (car cols))
         (princ "...")
         (setq cols (cdr cols)))
       (princ "\n"))

(print "===== Version #1: Base case - becomes (1 2 3) =====")
(process-args (car command-line-args-left) 1 2 3)

(print "===== Version #2: Passing cdr of list as one string =====")
(process-args (car command-line-args-left) (mapconcat 'identity (cdr command-line-args-left) " "));

(print "===== Version #3: Test of list of list - becomes ((1 2 3)) =====")
(process-args (car command-line-args-left) '(1 2 3))

最佳答案

您可以嘗試使用 'apply 展平最後一個參數('apply'的最後一個參數是參數列表,如果列表中沒有最後一位,請使用'funcall`)。

因此,上面的版本#3將被處理:

(apply 'process-args (car command-line-args-left) '(1 2 3))

(其他調用不會改變。)

轉載註明原文: 處理命令行args-left?