Julia Language Input Reading a String from Standard Input


Example

The STDIN stream in Julia refers to standard input. This can represent either user input, for interactive command-line programs, or input from a file or pipeline that has been redirected into the program.

The readline function, when not provided any arguments, will read data from STDIN until a newline is encountered, or the STDIN stream enters the end-of-file state. These two cases can be distinguished by whether the \n character has been read as the final character:

julia> readline()
some stuff
"some stuff\n"

julia> readline()  # Ctrl-D pressed to send EOF signal here
""

Often, for interactive programs, we do not care about the EOF state, and just want a string. For instance, we may prompt the user for input:

function askname()
    print("Enter your name: ")
    readline()
end

This is not quite satisfactory, however, because of the additional newline:

julia> askname()
Enter your name: Julia
"Julia\n"

The chomp function is available to remove up to one trailing newline off a string. For example:

julia> chomp("Hello, World!")
"Hello, World!"

julia> chomp("Hello, World!\n")
"Hello, World!"

We may therefore augment our function with chomp so that the result is as expected:

function askname()
    print("Enter your name: ")
    chomp(readline())
end

which has a more desirable result:

julia> askname()
Enter your name: Julia
"Julia"

Sometimes, we may wish to read as many lines as is possible (until the input stream enters the end-of-file state). The readlines function provides that capability.

julia> readlines()  # note Ctrl-D is pressed after the last line
A, B, C, D, E, F, G
H, I, J, K, LMNO, P
Q, R, S
T, U, V
W, X  
Y, Z
6-element Array{String,1}:
 "A, B, C, D, E, F, G\n"
 "H, I, J, K, LMNO, P\n"
 "Q, R, S\n"
 "T, U, V\n"
 "W, X\n"
 "Y, Z\n"
0.5.0

Once again, if we dislike the newlines at the end of lines read by readlines, we can use the chomp function to remove them. This time, we broadcast the chomp function across the entire array:

julia> chomp.(readlines())
A, B, C, D, E, F, G
H, I, J, K, LMNO, P
Q, R, S
T, U, V
W, X  
Y, Z
6-element Array{String,1}:
 "A, B, C, D, E, F, G"
 "H, I, J, K, LMNO, P"
 "Q, R, S"            
 "T, U, V"            
 "W, X  "             
 "Y, Z"               

Other times, we may not care about lines at all, and simply want to read as much as possible as a single string. The readstring function accomplishes this:

julia> readstring(STDIN)
If music be the food of love, play on,
Give me excess of it; that surfeiting,
The appetite may sicken, and so die.  # [END OF INPUT]
"If music be the food of love, play on,\nGive me excess of it; that surfeiting,\nThe appetite may sicken, and so die.\n"

(the # [END OF INPUT] is not part of the original input; it has been added for clarity.)

Note that readstring must be passed the STDIN argument.