sujingjhong.com


Elixir101 / Hello World

本文原刊載於個人 Medium

最近開始接觸 Elixir 這門語言,語法風格接近 Ruby。而他有一種動靜皆備的特性,老實說還蠻吸引我的。

因為 Elixir 可以用副檔名來區別是要直譯還是編譯,而它的 Elixir 的檔名主要有三種:.ex .exs .beam

這三種檔名差異,可以直接看官方說明

In addition to the Elixir file extension .ex, Elixir also supports .exs files for scripting. Elixir treats both files exactly the same way, the only difference is in intention. .ex files are meant to be compiled while .exs files are used for scripting. When executed, both extensions compile and load their modules into memory, although only .ex files write their bytecode to disk in the format of .beam files.

Elixir 對於不管是 ex 或者是 exs 檔案,都會將他們編譯後執行;只是在 ex 檔案,Elixir 會將他們寫成 beam格式的二元組碼到硬碟。

不過就像當初接觸 JavaScript 一樣,開始踩了很多坑,並且 Elixir 中文文件並沒有很多,故且將這個學習過程記錄一下,為這門語言貢獻一絲心力。

而學程式語言免不其然傳統上要由 Hello World開始,所以本篇文章將介紹三種方式的 Elixir Hello Word,分別是直接輸入指令、模組引用以及執行檔案。

第一種:直接輸入指令 #

第一種方法就是在 Elixir 的互動介面 iex 中輸入 IO.puts("Hello World")

$ iex
Erlang/OTP 21 [erts-10.0.5] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe] [dtrace]

Interactive Elixir (1.7.2) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> IO.puts("Hello World")
Hello World
:ok
iex(2)>

這裡要提一點是,在 iex 裡面有 IntelliSense

$ iex
Erlang/OTP 21 [erts-10.0.5] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe] [dtrace]

Interactive Elixir (1.7.2) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> IO.
ANSI                    Stream                  StreamError
binread/1               binread/2               binstream/2
binwrite/1              binwrite/2              chardata_to_string/1
getn/1                  getn/2                  getn/3
gets/1                  gets/2                  inspect/1
inspect/2               inspect/3               iodata_length/1
iodata_to_binary/1      puts/1                  puts/2
read/1                  read/2                  stream/2
warn/1                  warn/2                  write/1
write/2
iex(1)> IO.

當你輸入 IO. 甚至是完全不輸入,然後按 TAB 之後,iex 就會提示有哪些語法可以使用,真是太聰明的。

第二種:執行檔案 #

第二種就是將 IO.puts("Hello World") 存成檔案來執行。

打開一個新的檔案,命名為hello.ex 接著在裡面輸入:

IO.puts("Hello World")

再來我們在命列裡面輸入 elixir hello.ex

$ elixir hello.ex
Hello World

成功了!

第三種:模組引用 #

至於要怎麼將 hello world 當一個模組來引用呢?首先我們必須先建立一個模組,在 Elixir 我們需要用 mix 來建立一個專案模組。

那我們就在終端機裡面輸入 mix new hello_world 這裡的 hello_world 是我們的專案模組名稱,

所以如果你專案名稱叫 hello_elixir 的話就要輸入 mix new hello_elixir。題外話,在 mix 他預設適用 snake case 的命名方式,所以如果用 - 連接的話,或者是用 camcel case,就會發生如下畫面:

$ mix new hello-world
** (Mix) Application name must start with a lowercase ASCII letter, followed by lowercase ASCII letters, numbers, or underscores, got: "hello-world". The application name is inferred from the path, if you'd like to explicitly name the application then use the "--app APP" option

$ mix new helloWorld
** (Mix) Application name must start with a lowercase ASCII letter, followed by lowercase ASCII letters, numbers, or underscores, got: "helloWorld". The application name is inferred from the path, if you'd like to explicitly name the application then use the "--app APP" option

輸入完後就會看到如下畫面:

$ mix new hello_world
* creating README.md
* creating .formatter.exs
* creating .gitignore
* creating mix.exs
* creating config
* creating config/config.exs
* creating lib
* creating lib/hello_world.ex
* creating test
* creating test/test_helper.exs
* creating test/hello_world_test.exs

Your Mix project was created successfully.
You can use "mix" to compile it, test it, and more:

    cd hello_world
    mix test

Run "mix help" for more commands.

看到最後那句 Run "mix help" for more commands. 就知道完成了,接著我們就可以用慣用的編輯器,將這個專案打開。打開後可以發現長這樣的資料夾結構:

elixir_hello_world_project

接著我們打開 lib/hello_world.ex檔案,會發現裡面長這樣:

defmodule HelloWorld do
  @moduledoc """
  Documentation for HelloWorld.
  """

  @doc """
  Hello world.

  ## Examples

      iex> HelloWorld.hello()
      :world

  """
  def hello do
    :world
  end
end

他很貼心在裡面告訴你這個東西要怎麼用,就是在 iex 裡面輸入 HelloWorld.hello 就可以使用 hello 這個方法。

至於要怎麼引用呢?就是先切換到 hello_world 資料夾底下,之後我們在終端機輸入 iex -S mix

$ cd hello_world
$ iex -S mix
Erlang/OTP 21 [erts-10.0.5] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe] [dtrace]

Compiling 1 file (.ex)
Generated hello_world app
Interactive Elixir (1.7.2) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)>

會看到比先前多了兩行,這代表 Elixir 編譯了一個檔案,產生了叫做 hello_word 的模組:

Compiling 1 file (.ex)
Generated hello_world app

接著我們照他的說明打上 HelloWorld.hello()

iex(1)> HelloWorld.hello()
:world
iex(2)>

:ok! hello world

本篇就到此結束了~