Perl has many special variables. These are used to set or retrieve certain values which affect the way your program runs. For instance, you can set a special variable to turn interpreter warnings on and off, or read a special variable to find out the command line arguments passed to your script.
Special variables can be scalars, arrays, or hashes. We'll look at some of each kind.
Special variables are discussed at length in chapter 2 of your Camel book (from page 127 onwards) and in the perlvar manual page. You may also like to look up the English module, which lets you use longer, more English-like names for special variables. You'll find this information in chapter 7, on page 403, or use perldoc English to read the module documentation.
The first special variable, and possibly the one you'll encounter most often, is called $_ ("dollar-underscore"), and it represents the current thing that your Perl script's working with - often a line of text or an element of a list or hash. It can be set explicitly, or it can be set implicitly by certain looping constructs (which we'll look at later).
The special variable $_ is often the default argument for functions in Perl. For instance, the print() function defaults to printing $_
$_ = "Hello, world!\n"; print; |
If you can think of Perl variables as being "nouns", then $_ is the pronoun "it".
There's more discussion of using $_ on page 131 of your Camel book.
Set $_ to a string like "Hello, world", then print it out by using the print() command's default argument
The answers to the above exercise are in exercises/answers/scalars2.pl.
Perl programs accept arbitrary arguments or parameters from the command line, like this:
perl printargs.pl foo bar baz |
This passes "foo", "bar" and "baz" as arguments into our program, where they end up in an array called @ARGV. Try this script, which you'll find in your directory. It's called exercises/printargs.pl.
#!/usr/bin/perl -w print "@ARGV\n"; |
To run the script, type:
% exercises/printargs.pl |
You should see "foo bar baz" printed out.
Modify your earlier array-printing script to print out the script's command line arguments instead of the names of your friends. Call your script by typing ./scriptname.pl firstarg secondarg thirdarg or similar.
The answers to the above exercise is in exercises/answers/argv.pl
Just as there are special scalars and arrays, there is a special hash called %ENV. This hash contains the names and values of environment variables. To view these variables under Unix, simply type setenv (C-type shells) or export (sh type shells) on the command line.
A user's home directory is stored in the environment variable HOME. Print out your own home directory.
The answer to the above can be found in exercises/answers/env.pl