3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Elixirで実行ファイルをビルドする 〜escript〜

Posted at

今回作る実行ファイルの仕様

  • 足し算と引き算ができる
  • 足し算: ./escript_experiment --add --v1 値 --v2 値
    実行例
    ./escript_experiment --add --v1 10 --v2 2
     12 
    
  • 引き算: ./escript_experiment --sub --v1 値 --v2 値
    実行例
    ./escript_experiment --sub --v1 10 --v2 2
    8
    
  • 上記以外はエラーメッセージを表示
    実行例
    ./escript_experiment --s --v1 10 --v2 2
    引数が間違っています
    

プロジェクト作成

$ mix new escript_experiment
$ cd escript_experiment

ソースを書く

lib/escript_experiment_cli.ex
defmodule EscriptExperiment.CLI do
  def main(args \\ []) do
    args
    |> OptionParser.parse(strict: [add: :boolean, sub: :boolean, v1: :integer, v2: :integer])
    |> calculation()
    |> IO.puts()
  end

  defp calculation({[add: true, v1: v1, v2: v2], [], []}), do: v1 + v2
  defp calculation({[sub: true, v1: v1, v2: v2], [], []}), do: v1 - v2
  defp calculation(_), do: "引数が間違っています"

end

mix.exs
defmodule EscriptExperiment.MixProject do
  use Mix.Project

  def project do
    [
      app: :escript_experiment,
      version: "0.1.0",
      escript: escript()
    ]
  end

  # Run "mix help compile.app" to learn about applications.
  def application do
    [
      extra_applications: [:logger]
    ]
  end

  defp escript do
    [main_module: EscriptExperiment.CLI]
  end

end  

ビルド

$ mix escript.build

実行

$ ./escript_experiment --add --v1 10 --v2 2
12
$ ./escript_experiment --sub --v1 10 --v2 2
8
$ ./escript_experiment --s --v1 10 --v2 2
引数が間違っています

ソース(github)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?