Storing file.read output to a variable

Hi Everyone,

Totally new to programming and am trying to read a file and pattern match against user input.

I have a file named text.txt that contains the following:

------------- show mac address-table -------------

          Mac Address Table
------------------------------------------------------------------

Vlan    Mac Address       Type        Ports      Moves   Last Move
----    -----------       ----        -----      -----   ---------
100    1234.5678.9101    DYNAMIC       Et5        10      13:13:11

Using File.read I can see the contents of the file. What I’d like to do is store the contents to a variable that I can call later to pattern match a users input.

Any insight would be greatly appreciated.

Rich

Well, according to the documentation of File.read/1, it returns either an :ok-tuple which second element is a binary with the files content or an :error-tuple which second element explains the failure.

So it should be sufficient to simply match on the return value in a case:

case File.read(path) do
  {:ok, content} -> do_something_with(content)
  {:error, reason} -> # do error handling
end

There is also a pipeable version available which does return the content directly but raises on error: File.read!/1 but be careful with it.


Please take some time to reformat your initial post according to markdown rules, especially the verbatim content of your file should be enclosed in code-fences (``` on separate lines right before and after that snippet).

1 Like

Hi Nobbz, thank you for the insight.