Search code examples
erlangerlang-otp

Erlang: How to pass a path string to a function?


I created a new file, based on OTP gen_server behaviour.

This is the begining of it:

-module(appender_server).
-behaviour(gen_server).

-export([start_link/1, stop/0]).
-export([init/1, handle_call/3, handle_cast/2]).

start_link(filePath) ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, filePath, []).

init(filePath) ->
    {ok, theFile} = file:open(filePath, [append]). % File is created if it does not exist.

...

The file compiled ok using c(appender_server).

When I try to call start_link function from the shell, like this:

appender_server:start_link("c:/temp/file.txt").

I get:

** exception error: no function clause matching appender_server:start_link("c:/temp/file.txt") (appender_server.erl, line 10)

What do I do wrong?


Solution

  • filePath is an atom--not a variable:

    7> is_atom(filePath).
    true
    

    In erlang, variables start with a capital letter. The only way erlang could match your function clause would be to call the function like this:

    appender_server:start_link(filePath)
    

    Here is an example:

    -module(a).
    -compile(export_all).
    
    go(x) -> io:format("Got the atom: x~n");
    go(y) -> io:format("Got the atom: y~n");
    go(X) -> io:format("Got: ~w~n", [X]).
    

    In the shell:

    3> c(a).
    a.erl:2: Warning: export_all flag enabled - all functions will be exported
    {ok,a}
    
    4> a:go(y).
    Got the atom: y
    ok
    
    5> a:go(x).
    Got the atom: x
    ok
    
    6> a:go(filePath). 
    Got: filePath
    ok
    
    7> a:go([1, 2, 3]).
    Got: [1,2,3]
    ok
    
    8>