In this tutorial, we will learn how to write first perl program and run it on various Operating Systems.
First Perl Program: Hello World
This is a simple perl program that prints Hello World!! on the screen.
#!/usr/bin/perl #this is a comment print "Hello World!!";
Here first instruction #!/usr/bin/perl tells Operating systems to run this program with the interpreter located at /usr/bin/perl.
As I explained in the perl introduction that perl is a high level language that uses normal english, the problem is that machine doesn’t understand this high level language , therefore in order to make this program understandable by machine, we must interpret it into machine language. Interpreter is what interpret this program into machine language.
Second instruction #this is a comment is a comment, whatever you write after hash(#) is considered as comment
Third instruction prints “Hello World!!”; prints Hello World!! on the screen. Note the semicolon(;) at the end of instruction, you must put a semicolon at the end of every instruction, this tells interpreter that the instruction is finished.
How to run the perl program?
In order to run the above program, copy the code into a text editor like notepad for windows, textedit for mac etc. and save the file with .pl extension. lets say we save the file as firstprogram.pl. You can save the program under any name. Perl doesn’t force you to use special kind of name, you are free to use any name you wish.
To run the program on Windows, open command prompt (cmd) and write the following command
perl c:\perl\bin\perl.exe firstprogram.pl
Note: The above method is for running the perl program using command prompt. Alternatively, if you are using Strawberry Perl or Active Perl then you can simply click run.
On Linux/Unix/Mac OS
To run the program on Linux, Unix or Mac OS. Run the following commands on terminal.
chmod +x firstprogram.pl ./firstprogram
How to specify version of Perl in the script?
There are certain cases where we want to specify the version of Perl to make our script work properly. For example, In perl 5.10 or later you can use “say” in place of “print”. This is the new feature which got introduced in Perl 5.10.
#!/usr/bin/perl say "Hello World!!";
However this will not work if you are using Perl version prior to 5.10. To resolve this, you can re-write the above program like this:
#!/usr/bin/perl use 5.010; say "Hello World!!";
With the help of use statement we specified the version of Perl, this program will only work in Perl 5.10 or later.
Note: Perl expects sub version in three digits, that is the reason we have mentioned 5.010, if you use 5.10 instead then the Perl thinks that the mentioned version is 5.100. Similarly if you want to specify version 5.11 then use 5.011 instead of 5.11 in program.