Previous section To contents Next section

1.3 Further improvements

Now, wouldn't it be nice if it said Hello world! instead of hello world ? But of course we don't want to make our program "incompatible" with the old version. Someone might need the program to work like it used to. Therefore we'll add a command line option that will make it type the old hello world. We also have to give the program the ability to choose what it should output based on the command line option. This is what it could look like:

#!/usr/local/bin/pike

int main(int argc, array(string) argv)
{
    if(argc > 1 && argv[1]=="--traditional")
    {
        write("hello world\n"); // old style
    }else{
        write("Hello world!\n"); // new style
    }
    return 0;
}
Let's run it:

	$ chmod +x hello_world.pike
	$ ./hello_world.pike
	Hello world!
	$ ./hello_world.pike --traditional
	hello world
	$ 
What is new in this version, then?
int main(int argc, array(string) argv)
In this version the space between the parenthesis has been filled. What it means is that main now takes two arguments. One is called argc, and is of the type int. The other is called argv and is a an array of strings.

The arguments to main are taken from the command line when the Pike program is executed. The first argument, argc, is how many words were written on the command line (including the command itself) and argv is an array formed by these words.

if(argc > 1 && argv[1] == "--traditional")
{
    write("hello world\n"); // old style
}else{
    write("Hello world!\n"); // new style
}
This is an if-else statement, it will execute what's between the first set of brackets if the expression between the parenthesis evaluate to something other than zero. Otherwise what's between the second set of brackets will be executed. Let's look at that expression:

argc > 1 && argv[1] == "--traditional"
Loosely translated, this means: argc is greater than one, and the second element in the array argv is equal to the string --traditional. Since argc is the number of words on the command line the first part is true only if there was anything after the program invocation.

Also note the comments:

write("hello world\n"); // old style
The // begins a comment which continues to the end of the line. Comments will be ignored by the computer when it reads the code. This allows to inform whoever might read your code (like yourself) of what the program does to make it easier to understand. Comments are also allowed to look like C-style comments, i.e. /* ... */, which can extend over several lines. The // comment only extends to the end of the line.


Previous section To contents Next section