5
\$\begingroup\$

I wanted to implement the cat function in Julia and I ran a few test cases but I am not sure if I am missing anything:

for line in eachline(STDIN)
    write(line)
end

It's really simple code and I tested it with the following test cases:

$ cat hello.txt | julia cat.jl 
first line
second line
third line

$ cat hello.jpg | julia cat.jl > hello2.jpg
$

and hello2.jpg was the same as hello.jpg.

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

I think this is a good approach.

Stylistically I think you've done a good job as well; you've use a descriptive variable name (line), good indentation (4 spaces is standard for Julia), and have made use of a function that returns an iterator, which will be more efficient for this purpose than, say, one that returns an array.

The only thing I would do differently is to replace write with print. I tend to reserve the former for writing to a file and use the latter for writing to STDOUT.

There are two alternative ways to do this that I can think of. I'll provide them for completeness.

  1. Read the entire input stream as a single string and print it to STDOUT. Note that this is quite impractical for large input streams.

    print(readall(STDIN))
    
  2. Read and print each character from the stream one at a time.

    while !eof(STDIN)
        print(read(STDIN, Char))
    end
    

    This may provide some benefit in efficiency over your approach if the input is very large and contains few to no newlines, since eachline returns an iterator over the lines of the input, where lines are delimited by newlines. If I'm not mistaken, all lines are read before the loop body executes.

Overall though, for practical purposes I think this is a fine approach. Nice job.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.