Perl has a HUGE assortment of special builtin variables available for use. "man perlvar" for a complete listing.
Lots of them borrowed from shell or awk or other tools, so many should seem familiar.
The "English" module provides more readable "english" versions of the funny puctuation vars.
#!/usr/bin/perl -w
@i = (1, 2, 3);
foreach (@i) {
print $_ * 3, "\n"; # work on each element in turn
}
use English; # import the functionality of the English module
# from now on in the script we can use other names
foreach (@i) {
print $ARG * 3, "\n"; # same, with "English" version of $_
}
Read the "perlvar" manpage for a more complete list and more detail.
$_, $ARG: the default variable for many functions and operations.
$., $INPUT_LINE_NUMBER, $NR: current line number from input, reset upon an explicit close().
#!/usr/local/bin/perl -w
while (<>) {
chop;
print "line $.: $_\n";
}
output:
$ vars.pl < vars.pl
line 1: #!/usr/local/bin/perl -w
line 2:
line 3: while (<>) {
line 4: chop;
line 5: print "line $.: $_\n";
line 6: }
line 7:
$/, $INPUT_RECORD_SEPARATOR, $RS: input record separator, "\n" by default, can be changed to read data differently.
$/ = ":"; # reset to read by fields
open MYDATA, "vars2data" or die "cannot open datafile, $!";
while ($dat = <MYDATA>) { # read one field at a time
chop($dat);
print "found: $dat\n";
}
close(MYDATA);
input:
a:b:c:def:g
output:
found: a
found: b
found: c
found: def
found: g
Set $/ to "" or "\n\n" to read by paragraphs separated by blank lines.
Set $/ to undef to read entire file into single scalar.
$,, $OUTPUT_FIELD_SEPARATOR, $OFS: what print puts between items it is printing, default is nothing.
$?, $CHILD_ERROR: status returned by last child process (closing a pipe, backticks, system)
$!, $OS_ERROR, $ERRNO: if used as a number: contains last error number; if used as a string: the errno message.
$|, $OUTPUT_AUTOFLUSH: If set to non-zero, forces flushing of output stream after every write/print on currently selected output. Use in CGI a lot.
$$, $PROCESS_ID, $PID: pid of script when running.
$0, $PROGRAM_NAME: name of process as invoked.