String #!/usr/bin/perl in Perl script

Very often you can see that the first line in the Perl script is #!/usr/bin/perl.

Here is an example of very simple program in Perl:

▶ Run

print 'Hello';

If you save this text to a file, and then execute in the console perl, the screen appears Hello.

The most interesting that if to remove from a file line #!/usr/bin/perl (write only one line print 'Hello';) and run this code using perl, the result will be exactly the same — on the screen appears Hello.

The command in the console perl says you have to run the interpreter perl and an argument to give him a line (the name of the file with the program code). When run this way, it doesn't matter if the file the first line #!/usr/bin/perl or not. The system starts perl, and this program takes a text file as text program in the Perl language.

But the team perl is not the only way how to run Perl script. Another option is to make this file executable and execute it.

Again take the text in which there is a special first line:

▶ Run

print 'Hello';

Save this text to a file and run in the console:

$ chmod a+x
$ ./

Command chmod a+x we set the file flag that it is an executable file (executable). And then with the command ./ said that they want to execute a file, which is in the current directory (the current directory is denoted by a dot, and /— this is the separator between directory and file name).

When you start ./ it is important that the first line in the file was #!/usr/bin/perl. If we'll delete this line from the file and try to run it ./, we get the error:

$ ./
./ line 1: print: command not found

When the Perl script runs as ./ is the first row in the file must be #!/usr/bin/perl.

When we run the executable file of the program using ./, the system somehow need to understand what you need to run this code (Mac OS and linux in this place does don't look at the file extension). That's just to ensure this understanding and is used this is the first string in a special format. Grille, exclamation point, and then the full path to the interpreter with which to run the code.

If you do not specify the file line #!/usr/bin/perl and execute the code using ./, the system will assume that the code written in the shell in which you work (for example, bash) and try to run the program in the programming language Perl like this text on bash.

This special string is not the specifics of the Perl programming language and the specificity of the system. For other programming languages also have a similar line #!/usr/bin/python, #!/usr/bin/lua , etc.

Total recommendation — the first line in the Perl script should always be #!/usr/bin/perl.

Other articles