0

If I write a simple Map in Elixir, for example:

person = %{ :name => "Bob", :age => 45}

and I save it as a script, for example

script.exs

How do I retrieve Bob's age after I compile the script with

elixir script.exs ?

Or, even better:

iex script.exs

If I then write person[:age]

It gives me an error:

** (CompileError) iex:1: undefined function person/0

Isn't it possible to use Maps like this in Elixir?

Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74
A. N. Other
  • 409
  • 4
  • 14
  • Probably not the most fastest solution but you can implement a module with a function that returns the required struct and then just compile that file inside the console using the `c` function -> `c("my_file.ex")` and use that function to retrieve the value. – NoDisplayName Sep 23 '19 at 15:11

1 Answers1

2

It's a bit hacky, but you can pass the script using the iex --dot-iex script.exs. See The .iex.exs file.

$ iex --dot-iex script.exs
Erlang/OTP 21 [erts-10.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe]

Interactive Elixir (1.9.1) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> person
%{age: 45, name: "Bob"}

How do I retrieve Bob's age after I compile the script with elixir script.exs?

Not sure what you mean here. After you run the script, the script has finished, so there's no way to retrieve any of the values (unless the script returns or sets the environment).

Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74
  • I meant to use the Map “interactively”, according to my needs, after Elixir loads it. Thus avoiding using a real database. (With all its pluses and minuses, of course). I hope this is clearer now – A. N. Other Sep 23 '19 at 15:28
  • 1
    It's still pretty unclear what you're asking. If you just want to get Bob's age in IEx, use this solution, then try your `person[:age]` in IEx (`person.age` should also work). Or are you saying you want to do something like this in an Elixir project you can use from one of your modules? – Brett Beatty Sep 23 '19 at 15:35
  • Just the 1st case you suggested, but after the script is loaded, person[:age] gave me an error, as I wrote. That’s why I asked the question. – A. N. Other Sep 23 '19 at 15:44
  • In other words, I’d like to use interactively an already written Map from a script, not having to re-write the Map each time. – A. N. Other Sep 23 '19 at 15:53
  • Yes, it gives me an error: undefined function person/0 – A. N. Other Sep 23 '19 at 15:55
  • It sounds like you've not read the first sentence of this answer, because that does what you want. :-) – Adam Millerchip Sep 23 '19 at 15:59
  • Sure, my fault. I had everything in a module, and it didn’t work. I deleted the module, and now it works perfectly. Thank you so much. – A. N. Other Sep 23 '19 at 16:03
  • What does the —dot-iex actually do? – A. N. Other Sep 23 '19 at 16:04
  • 1
    That information is in the official docs linked from the second sentence. ;-) – Adam Millerchip Sep 23 '19 at 16:09