Hanan
Hanan

Reputation: 33

printing a special character in Erlang

I'm new to Erlang, I was wondering if there's a way to print a special character like # to the output without ' ', I want to print #, the relevant code is:

case {a(N),b(N)} of
    {false,_} -> {false,'#'};

but the output looks like: {false,'#'}, is there a way to get # instead of '#'?

Upvotes: 1

Views: 1450

Answers (2)

Pascal
Pascal

Reputation: 14042

With the example you give, you do not print anything, what you are showing is what the shell will output automatically: the result of the last statement. If you want to print something with a given format you have to call an io function:

1> io:format("~p~n",["#"]). % the pretty print format will show you are printing a string
"#"
ok
2> io:format("~s~n",["#"]). % the string format is used to print strings as text
#
ok
3> io:format("~c~n",[$#]). % the character format is used to print a charater as text 
#
ok
4> io:format("~p~n",[{{false,$#}}]). % note that a character is an integer in erlang.
{{false,35}}
ok
5> io:format("~p~n",[{{false,'#'}}]). % '#' is an atom, not an integer, it cannot be print as # without '
                                      % because it doesn't start by a lower case character, and also
                                      % because # has a special meaning in erlang syntax
{{false,'#'}}
ok
6> io:format("~p~n",[{{false,'a#'}}]).
{{false,'a#'}}
ok
7> io:format("~p~n",[{{false,'ab'}}]).
{{false,ab}}
ok
8> io:format("~p~n",[{{false,a#}}]).  
* 1: syntax error before: '}'
8>

Note that each time the shell print the result of the last statement: io:format/2 returns ok

Upvotes: 0

Vinod
Vinod

Reputation: 2243

In Erlang single quote is used to denote an atom. So '#' becomes an atom instead of special character.

You might have to consider the value using $# which would represent a # character or "#" would represent a string (string is a list of characters in Erlang).

In that case {false, $#} would result in {false, 35} (Ascii value of $#). If you want to print the character then you need to use io:format.

1> io:format("~c~n",[$#]).
#
ok

If you use string (list of chars) then:

2> io:format("~s~n",["#"]).
#
ok

Where ok is the return value of io:format.

Upvotes: 3

Related Questions