Perl to Lisp

文字列処理はだいたいPerlでやることが多いんだけど、諸事情でEmacs上でできた方が便利なときがあって、そのためのメモ。

  • m//

==> string-match

  • s///

==> string-matchしてreplace-match

  • split

==> split-string

  • join

==> mapconcat

  • while (<>) {}
(defun for-each-lines (func str)
  (if str
      (mapc func (split-string str "[\n]"))
    (save-excursion
      (goto-char (point-min))
      (while (< (point) (point-max))
        (let ((line (buffer-substring-no-properties (line-beginning-position)
                                                    (line-end-position))))
          (funcall func line) result)
        (and (zerop (forward-line)) (end-of-line))))))

あるいは、(こっちの方がLisp的)

(defun map-lines (func str)
  (if str
      (mapcar func (split-string str "[\n]"))
    (let (result)
      (save-excursion
        (goto-char (point-min))
        (while (< (point) (point-max))
          (let ((line (buffer-substring-no-properties (line-beginning-position)
                                                      (line-end-position))))
            (push (funcall func line) result))
          (and (zerop (forward-line)) (end-of-line))))
      (nreverse result))))

いま気がついた。これだと改行の扱いがいい加減で、データに含まれたり含まれなかったりするな。