[mercury-users] Perl split, assign, retrieve in Mercury
Ralph Becket
rbeck at microsoft.com
Mon Jul 16 18:59:34 AEST 2001
> From: Terrence Brannon [mailto:tmbranno at oracle.com]
> Sent: 13 July 2001 19:41
>
> A very common and easy thing to do in Perl is to read a file and split
> each line on a delimiter and assign each element of the line to a
> member of a hash and then obtain some member of the hash for
> processing of some sort. A typical Perl program for this task is
> included below. How would this be done in Mercury?
>
> while (<DATA>) {
>
> @split{letters, numbers, junk} = split /:/;
> print $split{numbers};
> }
I've been putting a small library together to support this sort of
Perl/Awk style file processing.
The code to read a line and split it according to a given separator
is
% Read a line in and split it. The line returned is empty (i.e. has
% zero elements) on EOF.
%
:- pred get_line(string, line, io__state, io__state).
:- mode get_line(in, out, di, uo) is det.
get_line(Separators, Line) -->
io__read_line_as_string(Result),
{ Result = ok(String), Line = split_string(Separators, String)
; Result = eof, Line = make_empty_array
; Result = error(E), throw(E)
}.
% split_string(" ", " the quick brown fox!") =
% array([" the quick brown fox!", "the", "quick", "brown",
"fox!"])
%
:- func split_string(string, string) = line.
split_string(Separators, Line) = array([Line | string__words(P, Line)])
:-
P = ( pred(C::in) is semidet :- string__contains_char(Separators, C)
).
To handle your example you'd read in the file line by line with
get_line(":", Line) and print out Line ^ elem(2) each time.
- Ralph
--------------------------------------------------------------------------
mercury-users mailing list
post: mercury-users at cs.mu.oz.au
administrative address: owner-mercury-users at cs.mu.oz.au
unsubscribe: Address: mercury-users-request at cs.mu.oz.au Message: unsubscribe
subscribe: Address: mercury-users-request at cs.mu.oz.au Message: subscribe
--------------------------------------------------------------------------
More information about the users
mailing list