Reputation: 1432
I am new to Elixir. I am trying to run a function inside a module. My code in the file is as follows:
defmodule greeter do
def print() do
IO.puts "Hello workd"
end
def print(name) do
IO.puts "Hello " <> name
end
defp print(name,age) do
IO.puts "Hello " <>name<>" My age is "<> age
end
end
greeter.print()
greeter.print("Xyxss")
When I run elixirc filename.ex
on my command line I get the following error:
warning: variable "greeter" does not exist and is being expanded to "greeter()", please use parentheses to remove the ambiguity or change the variable name
functions.ex:1
== Compilation error in file functions.ex ==
** (CompileError) functions.ex:1: undefined function greeter/0
(stdlib) lists.erl:1354: :lists.mapfoldl/3
(elixir) expanding macro: Kernel.defmodule/2
functions.ex:1: (file)
I am unable to solve the given error. Can somebody help me with this?
Upvotes: 2
Views: 1059
Reputation: 121000
I would put a correct answer here, since the answer provided by @J.Sebio is plain wrong.
The module name in Elixir must be an atom. Both examples below work perfectly:
iex(1)> defmodule :foo, do: def yo, do: IO.puts "YO"
iex(2)> :foo.yo
YO
iex(3)> defmodule :"42", do: def yo, do: IO.puts "YO"
iex(4)> :"42".yo
YO
The thing is: in Elixir, capitalized term is an atom:
iex(5)> is_atom(Greeting)
true
That is why capitalizing the name of the module worked. Also, greeting
is a plain variable, that is why the compiler tries to resolve it inplace and throws an error.
Upvotes: 1
Reputation: 114
In elixir the modules are written capitalized, and normally written CamelCase
, so, in your case you have to rewrite your code to:
defmodule Greeter do
def print() do
IO.puts "Hello workd"
end
def print(name) do
IO.puts "Hello " <> name
end
defp print(name,age) do
IO.puts "Hello " <>name<>" My age is "<> age
end
end
Greeter.print()
Greeter.print("Xyxss")
Upvotes: 0