2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

草莽Erlang ── 08. 標準入出力

Last updated at Posted at 2023-01-05

口で言うより行うことがErlang習得への近道と信じています。

標準入出力関連の関数

標準入出力関連の関数は、io モジュールにあります。いくつか取り上げてみます。

キーボード入力された文字列を取得

io:get_line/1 で標準入力にキーボード入力された文字列を取得できます。

> Input = io:get_line("名前を入力してください: ").
名前を入力してください: Inoki
"Inoki\n"

string:chomp/1 で文字列の末尾に改行文字を改行文字を削除します。

> string:chomp(Input).
"Inoki"

標準出力へ印字

いろんな技があるようです。

io:put_chars/1を使うと文字列を印字できます。文字列じゃないとエラーになるので注意が必要です。

> io:put_chars(["hello", $\n]).
hello
ok

> io:put_chars("闘魂\n").
闘魂
ok

% 文字列じゃないのでエラー
> io:put_chars({1, 2}).
** exception error: bad argument
     in function  io:put_chars/1
        called as io:put_chars({1,2})
        *** argument 1: not valid character data (an iodata term)

io:format/2を使うといろんな型のデータに対してフォーマットを整えて印字できます。

文字列を直接渡すことができます。Erlangの文字列はリストです。

> io:format("Hello, world\n").
Hello, world
ok

> io:format("闘魂, world\n").
闘魂, world

> io:format([[["闘", "魂"], ", ", "world"], $\n]).
闘魂, world
ok

sで文字列を整えることができます。

% 文字列の最初の5文字だけ印字
> io:format("~5s~n", ["hello world"]).
hello
ok

% 文字列を5文字分の範囲で右よせ
> io:format("|~5s|~n", ["123"]).
|  123|
ok

% 文字列を5文字分の範囲で左よせ
> io:format("|~-5s|~n", ["123"]).
|123  |
ok

sで多バイトの文字に対応するためにはUnicode translation modifier(t)を指定する必要があります。

% 何もしないと多バイトの文字がエラーを引き起こす
> io:format("~s~n", ["闘魂"]).
** exception error: bad argument
     in function  io:format/2
        called as io:format("~s~n",[[38360,39746]])
        *** argument 1: failed to format string

% Unicode translation modifierをつけて一件落着
> io:format("~ts~n", ["闘魂"]).
闘魂
ok

fで浮動小数点数を整えることができます。初期設定では小数点以下6桁が印字されます。

> io:format("~f seconds~n", [30.99]).
30.990000 seconds
ok

> io:format("~.3f seconds~n", [30.99]).
30.990 seconds
ok

pで何でも印字。ただしコードが印字されるイメージなので注意。文字列については専用のsを使ったほうがよさそうです。

% タプル
> io:format("~p~n", [{1, 2, 3}]).
{1,2,3}
ok

% マップ
> io:format("~p~n", [#{id => 123, name => "Inoki"}]).
#{id => 123,name => "Inoki"}
ok

% 数字
> io:format("~p~n", [123]).
123
ok

> io:format("~p~n", [123.45]).
123.45
ok

% 文字列
> io:format("~p~n", ["hello"]).
"hello"
ok

> io:format("~p~n", ["闘魂"]).
[38360,39746]
ok

標準出力に印字せず、フォーマットされた文字列を生成したいだけの場合は、io モジュールの代わりにio_libモジュールを使うといいかもしれません。

> io_lib:format("My number is ~p", [123]).
[77,121,32,110,117,109,98,101,114,32,105,115,32,"123"]

文字列操作のための関数はstringモジュールにあります。

Elixirにも挑戦したい

闘魂ElixirシリーズとElixir Schoolがオススメです。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?