Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

elixir

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?

like image 909
Thomas Browne Avatar asked Aug 29 '16 14:08

Thomas Browne


2 Answers

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, ...]
like image 51
Dogbert Avatar answered Oct 31 '22 11:10

Dogbert


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.

like image 3
mentels Avatar answered Oct 31 '22 12:10

mentels