Skip to content

Instantly share code, notes, and snippets.

@okeuday
Created April 5, 2019 06:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save okeuday/0fc551e2a5b1f346d64646d2cd2b66c7 to your computer and use it in GitHub Desktop.
Save okeuday/0fc551e2a5b1f346d64646d2cd2b66c7 to your computer and use it in GitHub Desktop.
A quine in Erlang
#!/usr/bin/env escript
%%!
%-*-Mode:erlang;coding:utf-8;tab-width:4;c-basic-offset:4;indent-tabs-mode:()-*-
% ex: set ft=erlang fenc=utf-8 sts=4 ts=4 sw=4 et:
-mode(compile).
main(["-i" | _]) ->
MagicNumber = 0,
GenerationName = filename:basename(escript:script_name()),
"quine" ++ GenerationIndexStr = GenerationName,
io:format("Hi, my name is \"~s\" (generation ~s)~n"
"my magic number is ~w!~n",
[GenerationName,GenerationIndexStr,MagicNumber]),
exit_code(0);
main([]) ->
Path = filename:dirname(?FILE),
"quine" ++ GenerationIndexStr = filename:basename(?FILE),
NewGenerationIndex = erlang:list_to_integer(GenerationIndexStr) + 1,
NewGenerationName = "quine" ++ erlang:integer_to_list(NewGenerationIndex),
{ok, GenerationCurrent} = file:read_file(?FILE),
S = erlang:integer_to_list(binary:decode_unsigned(
crypto:strong_rand_bytes(2))),
GenerationNew = re:replace(GenerationCurrent,
"MagicNumber = [0-9]+,",
"MagicNumber = " ++ S ++ ",",
[global, {return, binary}]),
FilePath = filename:join(Path,NewGenerationName),
ok = file:write_file(FilePath,GenerationNew),
ok = file:change_mode(FilePath,8#00775),
io:format("~s is born!~n", [NewGenerationName]),
exit_code(0).
exit_code(ExitCode) ->
erlang:halt(ExitCode, [{flush, true}]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment