Archive

Posts Tagged ‘hrl’

How to create and manipulate records

March 9th, 2009

As I remember the first time I was tought about Object-Oriented paradigm, my teacher told me “everything around you is an object” … Damn, since then I couldn’t get rid of that even when programming with Erlang.

People say Records concept in Erlang is very similar to struct in C. That’s true, but for me, it looks rather like an Object

Normally, records are defined in a separate file with extension .hrl and included in the main module file.

person.hrl

%% person.hrl
-record(person, {name, age}).

Here I define a record, named person, which has 2 attributes name and age. I’ll use erl console to do some manipulation with record person

1> rr("person.hrl").
[person]
2> X = #person{name="Jonny", age="18"}.
#person{name = "Jonny",age = "18"}
3> X#person.name.
"Jonny"
4> X#person.age.
"18"
5> #person{name=Name} = X.
#person{name = "Jonny",age = "18"}
6> Name.
"Jonny"

1> I read record person defined in person.hrl
2> I created a new “object” of type person and assigned to variable X
3> I printed value of the attribute name from “object” X
4> I printed value of the attribute age from “object” X
5> I used pattern matching to extract value of the attribute name out of “object” X and assigned to variable Name
6> I printed value of variable Name

Basic ,