in reply to Curious about a quirk with the special variable, $0
a) It's often useful to know what name your script has. For example:
my $input_file = shift @ARGV; my $output_file = shift @ARGV; die "Usage: $0 INPUT OUTPUT\n" unless defined $input_file && defined $output_file;
OK, you could replace $0 by hard-coding your script's filename, but what if somebody goes and renames your script - then your helpful error message is not so helpful anymore.
jethro also mentions scripts that do different things depending on what they're named. (And you'd typically give the script multiple names using symbolic links on Unix-like filesystems.) lwp-request is a commonly installed example of a script that does precisely that.
Lastly, on some operating systems it is possible to assign to $0. That is, you can do:
$0 = "blah";
And when people look at a list of processes running on the system (e.g. the top or ps commands on Linux) they'll see "blah" instead of the real name of the script. This is occasionally useful. For example, you have a script "http-server.pl" which opens up an HTTP server on a random TCP port. Then you just do:
$0 = "http-server.pl [port $port]";
And then the port it's serving on is shown in top and ps, which will be useful if you're running several HTTP servers at once, and need to check how much memory they are each consuming.
b) special variables, like $0 are pre-declared. You don't need to declare them.
c) Perl doesn't differentiate between numeric and other scalar values (e.g. strings) unless it really has to. Strings that don't look like a number are treated as "0" if used in a numeric context.
Thus, usually $0 will equal 0 if used in a numeric context. However, try renaming your script to "4count.pl" and you'll notice that its behaviour changes.
|
|---|