在vim中快速執行erlang腳本

最近打算下定決心學習使用erlang, 不過我有點不習慣在erlang shell和vim之間來回切換。
想了想,乾脆優化一下這個重複的過程吧。就像我配置了python的執行快捷鍵同樣,每次只要按下F6, 就會執行當前編輯的python腳本,並新開一個terminal,輸出程序正常打印的信息或錯誤信息python

編寫Hello world 腳本

-module(hello).
-export([say/0, main/0, hi/1]).


hi(Name) ->
    io:format("hi ~s~n",Name).

say() ->
    io:format("hello world~n").

main()->
    io:format("main~n"),
    say().

Erlang執行腳本的方法

  1. erlang shell中執行erl進入erlang shell
    $ erl
    Erlang/OTP 22 [erts-10.5] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe]
    Eshell V10.5 (abort with ^G)
    1> c(hello).
    {ok,hello}
    2> hello:say().
    hello world
    ok
  2. 在shell中執行 $ erlc hello.erl
    $ erl -noshell -s hello say -s init stop erlc從命令行和啓動了erlang編譯器,編譯器編譯了hello.erl
    並生成一個名爲hello.beam的目標代碼文件 erl -noshell … 加載了hello模塊並執行了hello:say()函數,最後,執行init:stop(),終止了erlang會話

這兩種都比較麻煩,有沒有更簡單一點的方法呢?做爲一個偷懶的程序猿,我確定不喜歡這樣重複的shell

個人解決方法

  1. /usr/local/bin/下建立一個可執行的bash腳本,假設名稱是exec_erl,內容以下
#!/bin/bash

erl_file_name=$1
shift
fun=$1
shift
if [ -z "$fun" ]; then
    fun=main
fi
erl_mode="${erl_file_name%.*}"
erlc ${erl_file_name}
erl -noshell -s $erl_mode $fun $@ -s init stop
  1. 修改vim配置文件
augroup filetype_erlang
    autocmd!
    autocmd Filetype erlang nnoremap <buffer> <F6> :w<CR>:ter   exec_erl %  <CR>
augroup END

小結

在編寫一個erlang腳本後,想快速驗證,只須要再多寫一個main函數並把他export出來,而後再main中調用你的測試方法, 按下F6就能夠運行了。vim

能夠愉快地debug腳本了. 其餘須要編譯的語言,也能夠用這個相似的方法解決,不過,應該都比erlang的簡單一些segmentfault

還有一個好處,若是想驗證某個方法,能夠直接在執行exec_erl filename.erl functionname param1 param2
例如,我想執行hello.erl中say()
exec_erl hello.erl say
若是想執行hi
exec_erl hello.erl hi zhangsanbash

最後,歡迎你們關注個人微信公衆號:匿名程序媛,你們一塊兒挖坑填坑。
image微信

相關文章
相關標籤/搜索