problem with byLine
Matt Soucy
msoucy at csh.rit.edu
Tue May 15 09:03:16 PDT 2012
On 05/15/2012 10:42 AM, dcoder wrote:
> On Monday, 14 May 2012 at 09:00:14 UTC, simendsjo wrote:
>> On Mon, 14 May 2012 10:41:54 +0200, Christian Köstlin
>> <christian.koestlin at gmail.com> wrote:
>>
>>> Hi,
>>>
>>> i wanted to output an ascii-file line by line, but reversed.
>>> the idea was to open the file, use byLine to read it line-by-line,
>>> make this range an array, and retro this array.
>>>
>>> But when i convert byLine to an array, the result is already trash.
>>>
>>> Please see this snippet.
>>>
>>> import std.stdio;
>>> import std.array;
>>>
>>> int main(string[] args) {
>>> if (args.length != 2) {
>>> throw new Exception("Usage: " ~ args[0] ~ " file1");
>>> }
>>>
>>> auto f = File(args[1], "r");
>>> auto i = array(f.byLine());
>>> foreach (l; i) {
>>> writeln(l);
>>> }
>>> return 0;
>>> }
>>>
>>> Any idea why this happens?
>>>
>>> regards
>>>
>>> christian köstlin
>>
>> I believe byLine reuses the internal buffer. Try duping the lines:
>> auto i = f.byLine().map!"a.idup"().array();
> Can someone please explain to me the last line?
>
> I'm trying to learn D, by playing with code and reading this forum. I'm
> a slow learner. :)
>
> Anyways, I looked at std.stdio code and noticed that byLine resturns a
> struct ByLine, but where does the .map come from? Thanks!
>
It comes from std.algorithm. What that line does is:
f.byLine() // Get by lines, exactly as you know already
.map!"a.idup"() // Iterate over the byLine, and make a Range of
immutable strings with the same contents as each line.
.array() // Convert it from a range to an array of strings
This is achieved through templates accepting strings at compile time to
be somewhat like lambda functions, and UFCS.
More information about the Digitalmars-d-learn
mailing list