Julia Learner
Julia Learner

Reputation: 2902

In Julia display a text file to the REPL

Given a text file, "hello.jl" in the current directory:

" Example hello world program."
function hello()
    println("hello, world")
end

how would you display this to the Julia 1.0.0 REPL?

This is what I have so far:

julia> disp(f) = for line in readlines(open(f)); println(line); end
disp (generic function with 1 method)

julia> disp("hello.jl")
" Example hello world program."
function hello()
        println("hello, world")
end

Is there a built-in command to do this in Julia?

Upvotes: 0

Views: 987

Answers (3)

Jayakrishnan Nair
Jayakrishnan Nair

Reputation: 81

println(String(read("hello.jl")))

or

"hello.jl" |> read |> String |> println

Upvotes: 3

Bill
Bill

Reputation: 6086

In the julia REPL, hit

;

to get to the REPL's built-in shell mode, then

shell> head path/to/my/filename

Upvotes: 2

HarmonicaMuse
HarmonicaMuse

Reputation: 7893

You can use the run function and pass it a Cmd argument, in Linux, to run the cat system command.

Type semicolon ; in order to change to shell mode:

shell> cat hello.jl
"Example hello world program."
function hello()
    println("hello, world")
end

Use the run function to execute a command outside of Julia:

julia> run(`cat hello.jl`)  # Only works on Unix like systems.
"Example hello world program."
function hello()
    println("hello, world")
end
Process(`cat hello.jl`, ProcessExited(0))

In Windows the type command should be analogous to Unix cat:

julia> show_file(path::AbstractString) = run(@static Sys.isunix() ? `cat $path` : `type $path`)
show_file (generic function with 1 method)

run returns the Process object:

julia> show_file("hello.jl")
"Example hello world program."
function hello()
    println("hello, world")
end
Process(`cat hello.jl`, ProcessExited(0))

Use semicolon ; at the end of the line, to suppress the return output in the REPL:

julia> show_file("hello.jl");  
"Example hello world program."
function hello()
    println("hello, world")
end

Or you could just return nothing at the end of show_file if you like.

Upvotes: 3

Related Questions