Quick Perl question for the experts

tmay's picture

They have: 75 posts

Joined: Sep 2001

Ok, I'm not having any problems with Perl, this question is just for personal gain and knowledgement.

Everybody knows the "#" sign is for comments and stuff because Perl ignores the line completely. Why does the most important line to Perl, the "shbang" line, start with a "#"?

I've always wondered that since I started learning Perl, but never asked.

-Troy May

PC Sympathy

Admin at HFT Online

tmay's picture

They have: 75 posts

Joined: Sep 2001

They have: 3 posts

Joined: Sep 2001

Well, apparently you figured it out, but to explain what I know about it:

Any shell script on a Unix system starts with a 'bang line', or 'shebang line'. This line is always a # sign, an ! mark, and the path to the interpretor.

#!/usr/bin/perl

The reason it starts with a # sign is that you can run this script through the interpretor directly -- in which case that line is simply ignored.

Perl never sees that line when a Perl script is executed directly. The operating system sees it, and decides it's a text-based script. It then finds the interpretor, and executes it, giving the script filename as an argument:

/usr/bin/perl scriptname.pl

The short answer is that Perl (or sh or other shell scripting language) will ignore the line, as it should. Only the system (or the web server) needs to interpret the line.

---
Little known facts:

- Most people don't know this, but it does not have to be the first line. You can have blank lines and comments before it, just no code.

- In most cases with Perl scripts, if you put a single hyphen as the last argument, you can forget about having to upload in ASCII mode:

#!/usr/bin/perl --

See, it's not Perl that cares about line terminations, Perl is cross-platform. It's the operating system that causes the problem; It sees the CR (carriage return) as being part of the command line, which when passed to perl is an invalid argument.

The last hyphen tells Perl to ignore the rest of the command line (over-simplified explanation); thus, when it sees the CR that Windows or MAC uses to terminate lines, it will simply ignore it instead of giving an error. If all scripts shipped like this, the most common script problem would simply go away Wink

But enough useless information...

merlin's picture

They have: 410 posts

Joined: Oct 1999

well, i didn't know all that stuff. thank you for the information (not as useless as you're saying... Wink )

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

Welcome to TWF, Jm4n!

Very usefull information, thanks!

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.