IO

IO in Elixir

1 esercizio

Informazioni su IO

Le funzioni per gestire input e output sono fornite dal modulo IO.

  • IO.puts/2 scrive una stringa sullo standard output, seguita da un carattere di nuova riga. Restituisce :ok.
  • IO.write/2 scrive una stringa sullo standard output, senza aggiungere un carattere di nuova riga. Restituisce :ok.
  • IO.gets/2 legge una riga dallo standard input.
  • IO.inspect/2 scrive qualsiasi cosa sullo standard output e accetta opzioni utili come :label. Restituisce invariato il valore ricevuto. Utile per il debug.

Il protocollo String.Chars

Se provi a passare a IO.puts/2 un valore che non riesce a stampare, vedrai un errore Protocol.UndefinedError.

IO.puts({:ok, 7})
# ** (Protocol.UndefinedError) protocol String.Chars not implemented for {:ok, 7} of type Tuple

Quando succede, potresti voler usare IO.inspect/2 al suo posto.

IO.inspect/2 per il debug

IO.inspect/2 è perfetto per il debug: restituisce invariato il suo argomento, può stampare qualsiasi cosa e offre un'opzione :label.

"HELLO\n"
|> String.trim()
|> IO.inspect(label: "step 1")
|> String.downcase()
|> IO.inspect(label: "step 2")

# > step 1: "HELLO"
# > step 2: "hello"
# => "hello"

I dispositivi IO

Il primo argomento di tutte queste funzioni è un dispositivo IO, con il valore predefinito :stdio (standard input/output). Per scrivere sul dispositivo di errore standard, usa invece :stderr. Un dispositivo IO può anche essere un processo, per esempio uno creato chiamando File.open/2, il che permetterebbe di scrivere su un file.

Modifica tramite GitHub Il collegamento si apre in una nuova finestra o scheda

Impara IO