LoginSignup
3
3

More than 3 years have passed since last update.

elixir公式のインストールからHello, World!まで[Mac OS]

Posted at

今更ですが、elixirはじめました。

インストール

elixirの公式サイトを参考に進めます。
https://elixir-lang.org/install.html#macos

HomebrewとMacportsの2通りありますが、
今回はHomebrewを使います。

環境

Mac: 10.12.4
Homebrew: 2.1.1(update前)
Homebrew: 2.1.6(update後)

Homebrewアップデート

$ brew update

エラーなくアップデートが完了

elixirのインストール

$ brew install elixir
==> Installing dependencies for elixir: openssl@1.1, libpng, libtiff, wxmac and erlang
(省略)

elixirの依存パッケージがインストールされます。
依存パッケージでerlangがインストールされているので、
erlangを使うことができます。

$ erl +V
Erlang (SMP,ASYNC_THREADS,HIPE) (BEAM) emulator version 10.4.3

Hello, World!

インタラクティブに

iexを使うことでコマンドライン上でやりとりしながら実行できます。
変数に文字列を代入して表示することもできます。

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

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

最初に出ているErlang/OTP 22 ~は、
Erlangのフレームワークのバージョン22を使用してることを表してるようです。
(初見時、エラーかと思いました。。。)

ファイル実行

拡張子

elixirで使用するファイルには主に3つ拡張子があります。

  • .ex: コンパイルするファイル
  • .beam: .コンパイル時に生成されるファイル
  • .exs: コンパイルせずに実行するファイル(スクリプトファイル)

exファイル(beamファイル)

ファイル作成

$ touch helloworld.ex

適当なエディタでファイルに記入

helloworld.ex
defmodule HelloWorld do
    def greet do
        IO.puts "Hello, World!"
    end
end

HelloWorld.greet

参考: The Elixir Style

コンパイルにはelixirc <ファイル名>を実行します。

$ elixirc helloworld.ex
Hello, World!

実行後、ディレクトリに実行ファイルが作成されています。

$ ls
Elixir.HelloWorld.beam  helloworld.ex

elixir -e <モジュール名>.<関数名>で実行できます。

$ elixir -e HelloWorld.greet
Hello, World!

exsファイル

先ほど作成したファイルをコピーします。

$ cp helloworld.ex helloworld.exs

スクリプトファイルの場合はelixir <ファイル名>を実行します。

$ elixir helloworld.exs
Hello, World!

先にコンパイルしていると以下のWarningが表示されますが、
beamファイルを削除することで表示されなくなります。

warning: redefining module HelloWorld (current version loaded from Elixir.HelloWorld.beam)

所感

インストールに時間がかからない点、
関数型言語にしては分かりやすい点で、お手軽な言語だと思いました。
PHPの文法をrubyにして、pythonを足した様な言語という所感です。

ちなみに、elixirに興味を持った理由は2つです。

  1. 株式会社アカツキ様のロマサガRSで使用していること
    (ロマサガRS における Elixir サーバー開発実践 ~生産性を上げてゲームの面白さに注力~)

  2. サーバーサイドの言語として新しいこと
    新しいものが好きです。
    (新しい言語は古い言語よりも勉強しやすいと個人的に思っています。)

elixirを学ぶのにいいサイトなどあれば、
コメントにて教えていただけると助かります!

参考

elixir
Elixir で Hello world!
Elixir入門の入門(インストール→「Hello, World!」を表示)

3
3
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
3
3