One usually starts by saying something to the audience. We do this using the say keyword. Not only does it print to the screen, it also adds a newline at the end of the string. As you can see strings are marked by double-quotes " at both their ends. The statements in Perl 6 end with semi-colon ;
#!/usr/bin/env perl6 use v6; say "Hello Perl 6 World";
The same can be written in Object Oriented style:
#!/usr/bin/env perl6 use v6; "Hello again Perl 6 World".say;
You could run either of these by typing perl6 hello_world.p6 or perl6 hello_world_oop.p6 respectively.
Actually you don't even need all the 3 lines, this example would also work if you ran it by writing perl6 hello_world_bare.p6.
say "Hello Perl 6 World";
The first line in the first example is called the hash-bang. In general it is not necessary, but if you would like to let the users run your Perl 6 code without explicitely typing in perl6 before the name of the script, then you need this line. At least on Unix/Linux systems. It tells the Unix/Linux shell you are using to look for the first executable called "perl6" in your PATH and run the script using that interpreter. In addition to the sh-bang line, you will also have to set the executable bit on the file. You do that by typing chmod u+x hello_world.p6. Once you have both, you can run your script as ./hello_world.p6. If the directory where the script is located is listed in the PATH environment variable, then you can even run it as hello_world.p6.
I used the file extension p6 to indicate this is a Perl 6 script though it is not necessary. Some people just use the regular pl extension. Actually the extension does not matter on Unix systems. It only matters as some editors base their syntax highlighting on the extension of the file.
This line tells perl that the following code requires Perl 6 or higher. The code will run correctly without this, if you run it with perl6. What happens if someone tries to run your script by mistake using perl 5? perl hell_world_bare.p6 and the output is:
String found where operator expected at books/examples/intro/hello_world_bare.p6 line 1, near "say "Hello Perl 6 World"" (Do you need to predeclare say?) syntax error at books/examples/intro/hello_world_bare.p6 line 1, near "say "Hello Perl 6 World"" Execution of books/examples/intro/hello_world_bare.p6 aborted due to compilation errors.
That looks bad. People will immediately come to you and tell you your code is broken!. You don't want to hear that do you?
So what happens if someone runs the code with the use v6; in it using perl 5? perl hello_world.p6 The output looks like this:
Perl v6.0.0 required--this is only v5.20.1, stopped at books/examples/intro/hello_world.p6 line 2. BEGIN failed--compilation aborted at books/examples/intro/hello_world.p6 line 2.
Now the problem is much clearer. (Though it would be nice if the error message printed by perl 5 was something like: This code requires Perl v6.0.0. You ran it using v5.20.1.
Published on 2012-01-01