unofficial mirror of guile-devel@gnu.org 
 help / color / mirror / Atom feed
* [PATCH v3] rdelim: Add new procedure `for-line-in-file`.
@ 2024-12-16  8:43 Adam Faiz
  2024-12-16 11:27 ` Tomas Volf
  2024-12-16 11:33 ` Ricardo Wurmus
  0 siblings, 2 replies; 5+ messages in thread
From: Adam Faiz @ 2024-12-16  8:43 UTC (permalink / raw)
  To: guile-devel; +Cc: Nala Ginrut, Ricardo Wurmus, Maxime Devos

From fe113e9efc08aae2a7e3792a1018c496212bd774 Mon Sep 17 00:00:00 2001
From: AwesomeAdam54321 <adam.faiz@disroot.org>
Date: Sun, 15 Dec 2024 23:48:30 +0800
Subject: [PATCH v3] rdelim: Add new procedure `for-line-in-file`.

* module/ice-9/rdelim.scm (for-line-in-file): Add it.

This procedure makes it convenient to do per-line processing of a text
file.
---
 module/ice-9/rdelim.scm | 23 ++++++++++++++++++++++-
 1 file changed, 22 insertions(+), 1 deletion(-)

diff --git a/module/ice-9/rdelim.scm b/module/ice-9/rdelim.scm
index d2cd081d7..b4c55c12e 100644
--- a/module/ice-9/rdelim.scm
+++ b/module/ice-9/rdelim.scm
@@ -23,7 +23,8 @@
 ;;; similar to (scsh rdelim) but somewhat incompatible.
 
 (define-module (ice-9 rdelim)
-  #:export (read-line
+  #:export (for-line-in-file
+            read-line
             read-line!
             read-delimited
             read-delimited!
@@ -206,3 +207,23 @@ characters to read.  By default, there is no limit."
 	      line)
       (else
        (error "unexpected handle-delim value: " handle-delim)))))
+
+(define* (for-line-in-file file proc
+                           #:key (encoding #f) (guess-encoding #f))
+  "Call PROC for every line in FILE until the eof-object is reached.
+FILE can either be a filename string or an already opened input port.
+The corresponding port is closed upon completion.
+
+The line provided to PROC is guaranteed to be a string."
+  (let ((port
+         (if (input-port? file)
+             file
+             (open-input-file file
+                              #:encoding encoding
+                              #:guess-encoding guess-encoding))))
+    (let loop ((line (read-line port)))
+      (cond ((eof-object? line)
+             (close-port port))
+            (else
+             (proc line)
+             (loop (read-line port)))))))
-- 
2.41.0



^ permalink raw reply related	[flat|nested] 5+ messages in thread

end of thread, other threads:[~2024-12-16 13:08 UTC | newest]

Thread overview: 5+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2024-12-16  8:43 [PATCH v3] rdelim: Add new procedure `for-line-in-file` Adam Faiz
2024-12-16 11:27 ` Tomas Volf
2024-12-16 13:08   ` Nala Ginrut
2024-12-16 11:33 ` Ricardo Wurmus
2024-12-16 12:18   ` Maxime Devos

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).