I am new to erlang and have a bit of a headache with the following scenario:
Take this code:
-module (so).
-export ( [foo/0] ).
bar () ->
receive
die -> ok;
Msg -> io:format ("I say ~p.~n", [Msg] )
end.
bar (Name) ->
receive
die -> ok;
Msg -> io:format ("~s says ~p.~n", [Name, Msg] )
end.
foo () ->
Bar = spawn (fun bar/0),
Bar ! "Hello",
Bar ! die,
Baz = spawn (?MODULE, bar, ["Alice"] ), % bar/1 not exported
Baz ! "Hello",
Baz ! die.
The process spawned with spawn/1
works fine, but the second process spawned with spawn/3
fails as expected because I haven't exported bar/1
and hence I get {undef,[{so,bar,["Alice"]}]}
. Both spawn functions that take a parameter list (spawn/3
and spawn/4
) also take a module name. But I don't want to export bar/1
, because it is only used internally and never needs to be invoked from outside the module.
How can I spawn a function with arguments without exporting it?
You can just put the call inside another fun
like this:
spawn(fun() -> bar("alice") end)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With