D语言起步
2007-12-8 我第一次接触D语言,尝试了一下,发现效率还蛮高的.1.在linux 下安装D语言编译器
D语言的编译器目前有2个,DMD和GDC,DMD比较容易配置,
可以从http://www.digitalmars.com/d/dcompiler.html下载最新版
我下载的是dmd.zip包
a. 直接解压dmd.zip包在根目录下 /dmd
b. 设置环境变量
在/etc/profile 文件后面添加一行
#vi /etc/profile
export PATH=$PATH:/dmd/bin
c. 使设置的环境变量生效
#source /etc/profile
2.写个helloWord 测试一下
a. #vi hello.d
void main()
{
printf("hello, world!");
}
b. #dmd hello.d
c. #./hello
3.不用编译直接当作脚本文件来运行
#!/dmd/bin/dmd -run
/* 声明为脚本文件,并且执行它的是dmd*/
/* Hello World in D
To compile:
dmd hello.d
or to optimize:
dmd -O -inline -release hello.d
*/
import std.stdio;
void main(char[][] args)
{
writefln("Hello World, Reloaded");
// auto type inference and built-in foreach
foreach (argc, argv; args)
{
// Object Oriented Programming
CmdLin cl = new CmdLin(argc, argv);
// Improved typesafe printf
writefln(cl.argnum, cl.suffix, " arg: %s", cl.argv);
// Automatic or explicit memory management
delete cl;
}
// Nested structs and classes
struct specs
{
// all members automatically initialized
int count, allocated;
}
// Nested functions can refer to outer
// variables like args
specs argspecs()
{
specs* s = new specs;
// no need for '->'
s.count = args.length; // get length of array with .length
s.allocated = typeof(args).sizeof; // built-in native type properties
foreach (argv; args)
s.allocated += argv.length * typeof(argv).sizeof;
return *s;
}
// built-in string and common string operations
writefln("argc = %d, " ~ "allocated = %d",
argspecs().count, argspecs().allocated);
}
class CmdLin
{
private int _argc;
private char[] _argv;
public:
this(int argc, char[] argv)// constructor
{
_argc = argc;
_argv = argv;
}
int argnum()
{
return _argc + 1;
}
char[] argv()
{
return _argv;
}
char[] suffix()
{
char[] suffix = "th";
switch (_argc)
{
case 0:
suffix = "st";
break;
case 1:
suffix = "nd";
break;
case 2:
suffix = "rd";
break;
default:
break;
}
return suffix;
}
}
保存为:scripttest.d
#chmod +x scripttest.d
#./scripttest.d
页:
[1]