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
#!/usr/bin/perl

print 'Hello';

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

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

The command in the console perl script.pl says you have to run the interpreter perl and an argument to give him a line script.pl (the name of the file with the program code). When run this way, it doesn't matter if the file script.pl 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 script.pl 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
#!/usr/bin/perl

print 'Hello';

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

$ chmod a+x script.pl
$ ./script.pl
Hello

Command chmod a+x script.pl we set the file flag that it is an executable file (executable). And then with the command ./script.pl said that they want to execute a file script.pl, 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 ./script.pl 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 ./script.pl, we get the error:

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

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

When we run the executable file of the program using ./script.pl, 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 ./script.pl, 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

Comments