e r l a n g : c o o k b o o k

/ Erlang.StringInterpolation

This Web


WebHome 
WebChanges 
TOC
NewRecipe 
WebTopicList 
WebStatistics 

All Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Erlang Links


Erlang.org
Erlang Wiki
ErlMan
Erlang Wiki
The Jungerl
Erlang-fr.org
Joe Armstrong
Lambda the Ultimate

Erlang Web Ring


[Prev]: Joe Armstrong's Page
[Next]: Joe Armstrong's Page

Interpolating Functions and Expressions Within Strings

Problem

You want to create string using a mixture of literals and computed values. For example you want to display the current date is the string "Today's date is "

Solution

Make use of Erlang's generic display procedure and variable argument list. For an easy case (displaying date and time), we can make use of the httpd_util:rfc1123_date function to get a string date, and the built-in concatenation (++) operator to construct the string we want:

1> BBBB = "Today's date and time is " ++ httpd_util:rfc1123_date() ++ ".\n".
"Today's date and time is Fri, 20 Aug 2004 22:03:13 GMT.\n"
Other cases require that you use the generic io_lib formatting functions to create strings with the data you want. For example, we could achive the same result as follows:
1> YEAR=2004.
2004
2> MONTH="Aug".
"Aug"
3> DAY=20.
20
4> DAYSTR="Fri".
"Fri"
5> io:fwrite("~s ~s, ~s ~w ~w.\n", ["Today's date is",
5>      DAYSTR, MONTH, DAY, YEAR]).
Today's date is Fri, Aug 20 2004.
If we wanted to be fancy, we could also use httpd_util:month function to get the correct month name:
6> MNTH=8.
8
7> io:fwrite("~s ~s, ~s ~w ~w\n",                                  
7> ["Today's date is", DAYSTR, httpd_util:month(MNTH), DAY, YEAR]).
Today's date is Fri, Aug 20 2004

Discussion

See Also

Contributors

Based on work by GordonWeakliem and NoelWelsh.

-- BrentAFulgham - 20 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: StringRecipes
TopicOrder: 100

 
 
Copyright © 2004 by the contributing authors. All material on the Erlang Cookbook web site is the property of the contributing authors.
This material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest