Learn Perl: #! (the hashbang)

You might've encountered some materials that encouraged you to start your Perl programs like this:


This is called hashbang or shebang and allows you to run your programs under Linux / Unix with ./program.pl instead of perl program.pl.

However, it might not be clear why even bother adding this line. A couple of facts:

  • this is completely optional, and often redundant

    Most scripts do not need this line. Programs usually have a single file that starts them, called entry point. Only scripts which are entry points should ever start with this line.

  • it won't work for everyone

    As shebangs contain absolute paths, they will only work for your specific case, and anyone who has the same configuration as you. There are many ways to have perl installed, as well as many operating system that perl runs on, which you can't take into account with a single line.

  • it can come in handy

    There are times when someone or something would want to run your script without knowing which interpreter should it use. That could also be you during writing your program, so that you save some keystrokes when running it. These are great cases where hashbang comes in handy, but still needs to be configured per environment to make sure the absolute filesystem path to the interpreter is correct.

To summarize, use it sparingly and it can become a valuable tool in your toolbox. Don't treat it as a mandatory part of your script, as it can render it meaningless. Certainly watch out for tutorials that use it in every single example, as they likely don't understand the very substance they're trying to teach.

Learn Perl is a series of articles targeting those who are just starting with the language. The goal is to explain some of the trickier yet commonly used parts of the syntax. See the whole series here. For a proper introduction to the language, please see the free Modern Perl book.

Comments? Suggestions? Send to feedback@brtastic.xyz
Published on 2021-05-15