Input and Command-Line Arguments
Prerequisites: Functions
Reading from the keyboard
readline() reads one line of text typed by the user (without the
newline):
# illustrative — waits for keyboard input
print("What's your name? ")
name = readline()
print("How old are you? ")
age = tryparse(Int, readline())
if age === nothing
println("That's not a number.")
else
println("Hi $name, next year you'll be $(age + 1).")
end
What's your name? Ada
How old are you? 36
Hi Ada, next year you'll be 37.
readline() always returns a String, so convert it with parse or
tryparse. x === nothing is the idiomatic way to test for nothing
(isnothing(x) also works).
Command-line arguments
Arguments after the script name arrive in the global vector ARGS, as
strings:
# illustrative — run as: julia greet.jl Ada 3
name = length(ARGS) >= 1 ? ARGS[1] : "world"
times = length(ARGS) >= 2 ? parse(Int, ARGS[2]) : 1
for _ in 1:times
println("Hello, $name!")
end
println("Script: ", PROGRAM_FILE)
Hello, Ada!
Hello, Ada!
Hello, Ada!
Script: greet.jl
PROGRAM_FILE holds the script's name. For real command-line tools,
the ArgParse.jl or Comonicon.jl packages parse options like
--verbose and generate help text.
Reading all of standard input
# illustrative — run as: echo "3 4 5" | julia sum.jl
nums = parse.(Int, split(read(stdin, String)))
println(sum(nums))
12
read(stdin, String) reads everything piped in. split breaks it into
words and parse.(Int, ...) converts each one.