Why does readln include the line terminator?

Steven Schveighoffer schveiguy at yahoo.com
Tue Apr 14 21:40:37 PDT 2009


On Wed, 15 Apr 2009 00:21:48 -0400, Andrei Alexandrescu  
<SeeWebsiteForEmail at erdani.org> wrote:

> Daniel Keep wrote:
>>  Andrei Alexandrescu wrote:
>>> Daniel Keep wrote:
>>>> Andrei Alexandrescu wrote:
>>>>> ...
>>>>>
>>>>> Right now readln preserves the separator. The newer File.byLine
>>>>> eliminates it by default and offers to keep it by calling
>>>>> File.byLine(KeepTerminator.yes). The allowed terminators are one
>>>>> character or a string. See
>>>>>
>>>>> http://erdani.dreamhosters.com/d/web/phobos/std_stdio.html#byLine
>>>>>
>>>>> I consider such an API adequate but insufficient; we need to add to  
>>>>> it.
>>>>>
>>>>>
>>>>> Andrei
>>>> Why not:
>>>>
>>>> char[] line, sep;
>>>> line = File.byLine();    // discard sep
>>>> line = File.byLine(sep); // pass sep out
>>>>
>>>> The separator is likely to be more useful once extracted.
>>> And how about when sep is elaborate (e.g. regex)?
>>>
>>> Andrei
>>  Whatever was matched.  If we have a file containing:
>>  "A.B,C"
>>  And we split lines using /[.,]/, then this:
>>
>>> char[] line, sep;
>>> line = File.byLine(sep);
>>> while( line != "" )
>>> {
>>>     writefln(`line = "%s", sep = "%s"`, line, sep);
>>>     line = File.byLine(sep);
>>> }
>>  Would output this:
>>
>>> line = "A", sep = "."
>>> line = "B", sep = ","
>>> line = "C", sep = ""
>>    -- Daniel
>
> Where did you specify the separator in the call to byLine?

I think he's not read the docs.  Consider this usage instead:

auto reader = file.byLine!("/[.,]/")();
// normal usage, doesn't return separators
foreach(line; reader)
{
...
}

// alternate usage, returns separators as well
while(!reader.empty)
{
   char[] sep;
   char[] line = reader.front(sep); // can't remember if this is what you  
decided on.
   ...
   reader.popFront(); // ditto
}

//Note that if foreach on ranges was extended to allow multiple parameters  
per pass, you could do:

foreach(sep, line; reader)
{
...
}

-Steve



More information about the Digitalmars-d mailing list