Skip to content

Instantly share code, notes, and snippets.

@okeuday

okeuday/quine0

Created Apr 5, 2019
Embed
What would you like to do?
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