Created
April 5, 2019 06:25
-
-
Save okeuday/0fc551e2a5b1f346d64646d2cd2b66c7 to your computer and use it in GitHub Desktop.
A quine in Erlang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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