Thomas Browne
Thomas Browne

Reputation: 24898

In Elixir REPL iex, how do I suppress long pattern matching results

In the Elixir repl, iex, when I do an assignment I get the result of the pattern match printed in yellow:

enter image description here

This is great until the pattern match is long, for example a file:

enter image description here

...and obviously if it's a large file it a) takes forever (not because of the read time, but to prep for printing the pattern match to screen), and then b) it scrolls for ages.

How can I suppress this behaviour, or limit the size of the pattern matching output?

Upvotes: 8

Views: 1644

Answers (3)

Sheharyar
Sheharyar

Reputation: 75740

While @dogbert's answer is the simplest solution, there's another interesting way of suppressing IEx output provided by IEx itself. Just call this function at the end:

IEx.dont_display_result

So, you can do this in IEx:

f = File.read!(my_large_file); IEx.dont_display_result

Upvotes: 2

mentels
mentels

Reputation: 196

How Elixir REPL prints your terms

Elixir REPL by default limits the length of an output to be printed:

iex(16)> Enum.to_list(1..100)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 
 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 
 42, 43, 44, 45, 46, 47, 48, 49, 50, ...]

You can change that by using the Kernel.inspect/2 function with the :limit option. For example, Kernel.inspect Enum.to_list(1..100), limit: :infinitywill print the whole list.

However, the :limit option does not apply to strings nor charlists and File.read/1 returns a string (UTF-8 encoded binary). But you can still limit the output printed by telling the inspect/2 to treat your string as normal sequence of bytes (just binary):

Kernel.inspect File.read!("a.txt"), limit: 60, binaries: :as_binaries

Going through the entire file with streams

To perform an operation on each line of your file, you could use Enum.each/2 over a Stream and pass it appropriate function:

File.stream!("a.txt") |> Enum.each fn line -> IO.puts line end

This code will simply print each line.

Upvotes: 4

Dogbert
Dogbert

Reputation: 222118

I just add another statement (; 0 is a nice short one) to the end of the expression for this which makes iex not print the output of the first expression, and only the last one:

iex(1)> a = Enum.to_list(1..100); 0
0
iex(2)> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
 43, 44, 45, 46, 47, 48, 49, 50, ...]

Upvotes: 10

Related Questions