In my progress of learning Elixir, I am trying to make a simple sigil to parse csv's.
I have managed to make a sigil to do this, however I cannot find a way to make it work with special characters, such as for example ;
.
defmodule CommaSigil do
def sigil_v(lines, []), do: parse(lines,",")
def sigil_v(lines, delimiter), do: parse(lines,"#{delimiter}")
defp parse(lines, delimiter) do
lines
|> String.rstrip
|> String.split("\n")
|> Enum.map fn line ->
String.split(line, delimiter)
end
end
end
defmodule Example do
import CommaSigil
def test do
~v"""
hello,world,again
1,2,3
"""
end
def test2 do
~v"""
helloxworldxagain
1x2x3
"""x
end
def test3 do
~v"""
hello;world;again
1;2;3
"""; # <-- Elixir does not care about the ';'
end
end
Example.test
|> IO.inspect
Example.test2
|> IO.inspect
Example.test3
|> IO.inspect
Can I escape the ;
character somehow, or is it not possible to do this?
Semi colon (;
) plays a special role in Elixir - it is used for delimiting multiple expressions on single line of code. Hence, I don't think you can escape it. In fact, you cannot use any of the Elixir special characters as modifiers as it can potentially result in compilation error.
Besides, Modifiers in sigils are kind of options for the logic of sigils. For example, i
is a modifier to do case-insensitive match in Regular expressions. Meaning of each modifier value is fixed for the given sigil's definition.
We should not use modifiers as a way to pass additional parameters to underlying sigil's function - as you are doing - using modifiers (x
, and ;
) to specify the character that should be used as delimiter to split string.
PS: Somewhat similar to the Sigil you have created, is available in Elixir - its called Word List - it uses modifiers to indicate return types - delimiter for splitting words, however, is fixed - it is always a space character.
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