Tuesday, September 1, 2009

Perl Reserved Words and Variables

Perl Reserved Words and Variables

[ Source : http://www.sarand.com/td/ref_perl_reserve.html ]

Reserved Literals
__END__ indicates the logical end of the script (^D and ^Z are synonyms)
__FILE__ current filename
__LINE__ current line number
Reserved Filehandles
<> Null filehanedle - input from either stdin, or files specified on the command line. Psuedonym for internal filehandle .
DATA read data only from the main script, but not from any required file or evaluated string.
STDERR Output to stderr
STDIN Input from stdin
STDOUT Output to stdout
Reserved Variables
$_ The default input and pattern-searching space. The following pairs are equivalent:
while (<>) {...} while ($_ = <>) {...} # only equivalent in while!
/^Subject:/ $_ =~ /^Subject:/
tr/a-z/A-Z/ $_ =~ tr/a-z/A-Z/
chop chop($_)
Also: $ARG
@_ The parameters passed to a subroutine. The array itself is local to the subroutine, but its values are references to the variables that are passed so updates to the members of the array will update the corresponding parameter value.
"><digit> Contains the subpattern from the corresponding set of parentheses in the last pattern matched, not counting patterns matched in nested blocks that have been exited already. These variables are all read-only.
$& The string matched by the last successful pattern match (not counting any matches hidden within a BLOCK or eval() enclosed by the current BLOCK). This variable is read-only.
Also: $MATCH
$` The string preceding whatever was matched by the last successful pattern match, not counting any matches hidden within a BLOCK or eval enclosed by the current BLOCK. This variable is read-only.
Also: $PREMATCH
$' The string following whatever was matched by the last successful pattern match (not counting any matches hidden within a BLOCK or eval() enclosed by the current BLOCK). Example:
$_ = 'abcdefghi';
/def/;
print "$`:$&:$'\n"; # prints abc:def:ghi
This variable is read-only.
Also: $POSTMATCH
$+ The last bracket matched by the last search pattern. This is useful if you don't know which of a set of alternative patterns matched. For example:
/Version: (.*)|Revision: (.*)/ && ($rev = $+);
This variable is read-only.
Also: $LAST_PAREN_MATCH
$* Set to 1 to do multiline matching within a string, 0 to tell Perl that it can assume that strings contain a single line, for the purpose of optimizing pattern matches. Pattern matches on strings containing multiple newlines can produce confusing results when " $* " is 0. Default is 0. Note that this variable only influences the interpretation of " ^ " and " $ ". A literal newline can be searched for even when $* == 0 . The '/m' modifier should be used instead when pattern matching.
Also: $MULTILINE_MATCHING
$. The current input line number of the last filehandle that was read. This variable should be considered read-only. Remember that only an explicit close on the filehandle resets the line number. Since " <> " never does an explicit close, line numbers increase across ARGV files.
Also: $NR, $INPUT_LINE_NUMBER, input_line_number HANDLE EXPR
$/ The input record separator, newline by default. Works like awk 's RS variable, including treating blank lines as delimiters if set to the null string. You may set it to a multicharacter string to match a multi-character delimiter. Note that setting it to "\n\n" means something slightly different than setting it to "" , if the file contains consecutive blank lines. Setting it to "" will treat two or more consecutive blank lines as a single blank line. Setting it to "\n\n" will blindly assume that the next input character belongs to the next paragraph, even if it's a newline.
undef $/;
$_ = ; # whole file now here
s/\n[ \t]+/ /g;
Also: $RS, $INPUT_RECORD_SEPARATOR, input_record_separator HANDLE EXPR
$| If set to nonzero, forces a flush after every write or print on the currently selected output channel. Default is 0. Note that STDOUT will typically be line buffered if output is to the terminal and block buffered otherwise. Setting this variable is useful primarily when you are outputting to a pipe, such as when you are running a Perl script under rsh and want to see the output as it's happening.
Also: $OUTPUT_AUTOFLUSH, autoflush HANDLE EXPR
$, The output field separator for the print operator. Ordinarily the print operator simply prints out the comma separated fields you specify. In order to get behavior more like awk, set this variable as you would set awk 's OFS variable to specify what is printed between fields.
Also: $OFS, $OUTPUT_FIELD_SEPARATOR, output_field_separator HANDLE EXPR
$\ The output record separator for the print operator. Ordinarily the print operator simply prints out the comma separated fields you specify, with no trailing newline or record separator assumed.
Also: $ORS, $OUTPUT_RECORD_SEPARATOR, output_record_separator HANDLE EXPR
$" Delimiter used when interpreting an array as a scalar. This value separates each element of the array in the resulting string - default a space.
Also: $LIST_SEPARATOR
$; The subscript separator for multi-dimensional array emulation, which can be declared directly in v.5. If you refer to a hash element as
$foo{$a,$b,$c}
it really means
$foo{join($;, $a, $b, $c)}
But don't put
@foo{$a,$b,$c} # a slice--note the @
which means
($foo{$a},$foo{$b},$foo{$c})
Default is "\034", the same as SUBSEP in awk . Note that if your keys contain binary data there might not be any safe value for " $; ".
Also: $SUBSEP, $SUBSCRIPT_SEPARATOR
$# The output format for printed numbers. The initial value is '%. 20g'. Deprecated in Perl 5.
Also: $OFMT
$% The current page number of the currently selected output channel.
Also: $FORMAT_PAGE_NUMBER, format_page_number HANDLE EXPR
$= The current page length (printable lines) of the currently selected output channel. Default is 60.
Also: $FORMAT_LINES_PER_PAGE, format_lines_per_page HANDLE EXPR
$- The number of lines left on the page of the currently selected output channel.
Also: $FORMAT_LINES_LEFT, format_lines_left HANDLE EXPR
$~ The name of the current report format for the currently selected output channel. Default is name of the filehandle.
Also: $FORMAT_NAME, format_name HANDLE EXPR
$^ The name of the current top-of-page format for the currently selected output channel. Default is name of the filehandle with _TOP appended.
Also: $FORMAT_TOP_NAME, format_top_name HANDLE EXPR
$: The current set of characters after which a string may be broken to fill continuation fields (starting with ^) in a format. Default is S<" \n-">, to break on whitespace or hyphens.
Also: $FORMAT_LINE_BREAK_CHARACTERS, format_line_break_characters HANDLE EXPR
$^ L What formats output to perform a formfeed. Default is \f.
Also: $FORMAT_FORMFEED, format_formfeed HANDLE EXPR
$^ A The current value of the write() accumulator for format() lines. A format contains formline() commands that put their result into $^ A . After calling its format, write() prints out the contents of $^ A and empties. So you never actually see the contents of $^ A unless you call formline() yourself and then look at it.
Also: $ACCUMULATOR
$? The status returned by the last pipe close, backtick ( `` ) command, or system() operator. Note that this is the status word returned by the wait() system call, so the exit value of the subprocess is actually ( $? >> 8 ). Thus on many systems, $? & 255 gives which signal, if any, the process died from, and whether there was a core dump.
Also: $CHILD_ERROR
$! If used in a numeric context, yields the current value of errno, with all the usual caveats. (This means that you shouldn't depend on the value of " $! " to be anything in particular unless you've gotten a specific error return indicating a system error.) If used in a string context, yields the corresponding system error string. You can assign to " $! " in order to set errno if, for instance, you want " $! " to return the string for error n , or you want to set the exit value for the die() operator.
Also: $ERRNO, $OS_ERROR
$@ The Perl syntax error message from the last eval() command. If null, the last eval() parsed and executed correctly (although the operations you invoked may have failed in the normal fashion).
Also: $EVAL_ERROR
$$ The process number of the Perl running this script.
Also: $PID, $PROCESS_ID
$< The real uid of this process.
Also: $UID, $REAL_USER_ID
">$> The effective uid of this process. Example:
$< = $>; # set real to effective uid
($<,$>) = ($>,$<); # swap real and effective uid
Also: $EUID, $EFFECTIVE_USER_ID
$( The real gid of this process. If you are on a machine that supports membership in multiple groups simultaneously, gives a space separated list of groups you are in. The first number is the one returned by getgid() , and the subsequent ones by getgroups() , one of which may be the same as the first number.
Also: $GID, $REAL_GROUP_ID
$) The effective gid of this process. If you are on a machine that supports membership in multiple groups simultaneously, gives a space separated list of groups you are in. The first number is the one returned by getegid() , and the subsequent ones by getgroups() , one of which may be the same as the first number.
Note: " $& lt; ", " $& gt; ", " $( " and " $) " can only be set on machines that support the corresponding set[re][ug] id() routine. " $( " and " $) " can only be swapped on machines supporting setregid() .
Also: $EGID, $EFFECTIVE_GROUP_ID
$0 Contains the name of the file containing the Perl script being executed. Assigning to " $0 " modifies the argument area that the ps(1) program sees. This is more useful as a way of indicating the current program state than it is for hiding the program you're running.
Also: $PROGRAM_NAME
$[ The index of the first element in an array, and of the first character in a substring. Default is 0, but you could set it to 1 to make Perl behave more like awk (or Fortran) when subscripting and when evaluating the index() and substr() functions.
As of Perl 5, assignment to " $[ " is treated as a compiler directive, and cannot influence the behavior of any other file. Its use is discouraged.
$] The string printed out when you say perl -v . It can be used to determine at the beginning of a script whether the perl interpreter executing the script is in the right range of versions. If used in a numeric context, returns the version + patchlevel / 1000. Example:
# see if getc is available
($version,$patchlevel) =
$] =~ /(\d+\.\d+).*\nPatch level: (\d+)/;
print STDERR "(No filename completion available.)\n"
if $version * 1000 + $patchlevel <>
or, used numerically,
warn "No checksumming!\n" if $] <>
Also: $PERL_VERSION
$^ D The current value of the debugging flags.
Also: $DEBUGGING
$^ F The maximum system file descriptor, ordinarily 2. System file descriptors are passed to exec() ed processes, while higher file descriptors are not. Also, during an open() , system file descriptors are preserved even if the open() fails. (Ordinary file descriptors are closed before the open() is attempted.) Note that the close-on-exec status of a file descriptor will be decided according to the value of $^ F at the time of the open, not the time of the exec.
Also: $SYSTEM_FD_MAX
$^ I The current value of the inplace-edit extension. Use undef to disable inplace editing.
Also: $INPLACE_EDIT
$^ P The internal flag that the debugger clears so that it doesn't debug itself. You could conceivable disable debugging yourself by clearing it.
Also: $PERLDB
$^ T The time at which the script began running, in seconds since the epoch (beginning of 1970). The values returned by the -M , -A and -C filetests are based on this value.
Also: $BASETIME
$^ W The current value of the warning switch, either TRUE or FALSE.
Also: $WARNING
$^ X The name that the Perl binary itself was executed as, from C's argv[0] .
Also: $EXECUTABLE_NAME
$ARGV The name of the current file when reading from <>.
@ARGV The array @ARGV contains the command line arguments intended for the script. Note that $# ARGV is the generally number of arguments minus one, since $ARGV [0] is the first argument, NOT the command name. See " $0 " for the command name.
@INC The array @INC contains the list of places to look for Perl scripts to be evaluated by the do EXPR , require , or use constructs. It initially consists of the arguments to any -I command line switches, followed by the default Perl library, probably "/usr/local/lib/perl", followed by ".", to represent the current directory.
%INC The hash %INC contains entries for each filename that has been included via do or require . The key is the filename you specified, and the value is the location of the file actually found. The require command uses this array to determine whether a given file has already been included.
$ENV {expr} The hash %ENV contains your current environment. Setting a value in ENV changes the environment for child processes.
$SIG {expr} The hash %SIG is used to set signal handlers for various signals.
Environment Variables
These are available as the '%ENV' hash, and retrieved as follows:
$variable = $ENV{'variable'};
The following are commonly used:
CONTENT_LENGTH The number of bytes of data passed through standard input via the POST method.
DOCUMENT_ROOT Path on the server to the web site (root URL) being accessed.
GATEWAY_INTERFACE Protocol used to communicate with the server.
HTTP_COOKIE The contents of all cookies that are visible to the script - each cookie delimited by a semicolon (';').
HTTP_USER_AGENT The name (eg. 'Mozilla') and version (eg. '4.03') of the browser used to access the server and the type of platform used by the browser (eg. 'Macintosh;I;PPC').
HTTP_REFERER The URL of the page that was being viewed when the script was accessed, either via a link or by direct entering o fthe URL. Can be used to check that the user has come from a recognised source, to help with security.
QUERY_STRING Holds the data input via the GET method.
REQUEST_METHOD Either "POST" or "GET", depending on what is set on the method attributes of the form tag. NB This value will be "POST" if method="POST", even if some data is passed via GET (eg. data appended directly to the action URL).
The following will cause both methods to be used, even though $REQUEST_METHOD="POST":
SERVER_SOFTWARE Name and version of the web server.

No comments: