Perl - Special Variables and Characters:

Perl uses some special variables to control various behaviors of functions. You can use special variables to hold the results of searches, the values of environment variables, and flags to control. Understanding these variables is crucial to programming effectively in Perl.

Variables That Affect Arrays

$"

When arrays are converted to strings, the elements are separated by spaces by default, which, for example, is what happens when arrays are printed. This variable allows you to specify any string as the list separator, which may be useful for output formatting or for other reasons.

#!/usr/bin/perl
$"=' ! ';
@names=(John, Johny, Jim);
print "@names\n";


The output will be :

        John ! Johny ! Jim


$[

This variable, which is usually set to a value of 0, represents the index of the first element in any array, and of the first character in a substring. Default is 0, but programmers who are used to using 1 as the index of the first element of an array could change the value of this variable to suit their preference.

Assignment to $[ is now treated as a compiler directive, and cannot influence the behavior of any other file. Its use is discouraged.

#!/usr/bin/perl
$[ = 0;
$_ = "grapeorangeapple";
$locate=index($_,"orange");
print "orange is located at: $locate\n";
$[=1;
$locate=index($_,"orange");
print "orange is located at: $locate\n";


The output will be:

       orange is located at: 5
       orange is located at: 6


$;

This variable is used in emulating multidimensional arrays. The value must be one that is not used by any element in the array. The default value is \034.

Perl 5 directly supports multidimensional arrays directly, so the use of $SUBSCRIPT_SEPARATOR ($;) is not necessary.



Variables Used with Files

$.

This variable holds the current record or line number of the last file handle that was read. It is read-only and will be reset to 0 when the file handle is closed. The variable counts lines cumulatively across all input files read with the <> construct because these are not closed explicitly.

#!/usr/bin/perl
open(F, "file.dat")||die "can't open";
print "The last file read had $. lines\n";
close(F);


The output will be :

The last file read had 10 lines


$/

By default, an input file is split into records, each of which comprises one line. The input-record separator is a newline character. This variable when set to null string, treats blank lines as delimiters. You may set it to a multi-character 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" means Perl will blindly assume that the next input character belongs to the next paragraph, even if it's a third newline.

#!/usr/bin/perl
undef $/;
open(F, "test.pl")||die "can't open";
$buffer=;
print "$buffer\n";
close(F);


Ouput will be the whole "test.pl" file

$|

This variable, if set to nonzero, will flush the output buffer after every write() or print() function. Default is 0, which on many systems means that STDOUT will default to being line buffered if output is to the terminal, and block buffered otherwise. If you have a need to flush a buffer immediately after setting $|, you may simply print ""; rather than waiting for the next print to flush it.

When the output file is a pipe, it is best to set autoflush on so that other programs can access the pipe immediately after each write or print operation.

#!/usr/bin/perl
select(STDERR);
$| = 1;
print "Autoflush setting for STDERR is $|\n";
select(STDOUT);
print "Autoflush setting for STDOUT is $|\n";


The output will be :

       Autoflush setting for STDERR is 1
       Autoflush setting for STDOUT is 0


$^F

By default, Perl treats three files as system files 0, 1, and 2-normally, STDIN, STDOUT, and STDERR. The value of $^F is 2 by default. System files are treated specially; in particular, the file descriptors are passed to exec() processes. Also, during an open, system file descriptors are preserved even if the open fails. 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 at the time of the exec.

#!/usr/bin/perl
print "The default for file descriptors is $^F\n";


The output will be :

      The default for file descriptors is 2


$ARGV

Holds the name of the current file being read when using the diamond operator (<>).

#!/usr/bin/perl
while (<>){
      print "$ARGV\n";
};


While running please run as "perl test.pl file.dat" where, file.dat should be an existing file under the same directory as the script.

DATA

This file handle refers to any data following __END__ containing the script.

STDERR

This file handle is used to send output to the standard error file. Normally, this is connected to the display, but it can be redirected if needed.

STDIN

This file handle is used to read input from the standard input file. Normally, this is connected to the keyboard, but it can be changed.

STDOUT

This file handle is used to send output to the standard output file. Normally, this is the display, but it can be changed.

Variables Used with Patterns/Regular Expressions


$&

This variable holds the string that was matched by the last successful pattern match. This variable is read-only.
#!/usr/bin/perl
$fruit = "orangepineapple";
$fruit=~/p[ein]*/;
print "I like $&\n";

The output will be :

       I like pine

$`

When a string is matched by pattern, the pattern is actually split into three parts: the part of the string before the match, the part of the string that matched, and the part of the string after the match. Any of these parts could be empty, of course. This variable refers to the part of the string before the match. This variable is read-only.

#!/usr/bin/perl
$fruit = "orangepineapple";
$fruit=~/pine/;
print "I like $'\n";

The output will be:

      I like apple


$+

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. In most contexts, you could simply use $1, $2, and so on rather than $+. When the pattern has a series of sets of parentheses as alternatives to be matched, using $+ is useful. This variable is read-only.

#!/usr/bin/perl
$fruit = "orangepineapplegrape";
$fruit=~/pine(.*)apple(.*)/;
print "The last match: $+\n";


The output will be :

The last match: grape


$*

Use of $* is now deprecated, and is allowed only for maintaining backwards compatibility with older versions of Perl. Use /m (and maybe /s) in the regular expression match instead. Set to 1 to do multi-line 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.
$

This group of variables ($1, $2, $3, and so on) holds the regular expression pattern memory. Each set of parentheses in a pattern stores the string that matches the components surrounded by the parentheses into one of the $ variables. These variables are all read-only.
#!/usr/bin/perl
$fruit = "grapeorangeapple";
$us=~/^(grape)(.*)(apple)$/;
print "I like $1, $2 and $3\n"


The output will be :

       grape, orange and apple

Variables Used with printing

$,

This variable can alter the behavior of the print() function. The default behavior of print(), when it is given a comma-separated list of arguments, is to print each argument with no output separator. You can use this variable to specify any string as a separator.

#!/usr/bin/perl
$,="\n";
print STDOUT apple,orange,grapes, "\n";


The ouput will be :

     apple
     orange
     grapes


$\

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. If a newline is required at the end, you must add it explicitly. You can use this record-separator variable to specify any string as the end-of-record string, and you most commonly set it to the newline character to avert the need for explicit newlines.

#!/usr/bin/perl
$\="\n";
print "No need for an explicit new line";
print "Isn't it cool!";


The ouput will be :

     No need for an explicit new line
     Isn't it cool!


$#

The default format for printed numbers. The default value is %.2g Use of $# is now deprecated. You should use printf instead. $# contains the output format for printed numbers.

#!/usr/bin/perl
print 1234.5678, "\n";
$#="%.5g";
print 1234.5678, "\n";


The output will be :

       1234.5678
       1234.6


Variables Used with processes

$$

In systems that support multiple processes, Perl can identify the process number of the Perl script current process (that is the process which is executing the Perl script itself) via this variable.

#!/usr/bin/perl
print "process ID is : $$\n";


The output will be :

    process ID is : 123


$?

The status returned by the last pipe close, backtick (``) command, or system() function. If a Perl script spawns child processes, you can examine their error codes by using this variable.

$0

This variable contains the name of the Perl script that is being executed. You can alter this variable if you want the script to identify itself to the operating system as having a particular name.

#!/usr/bin/perl
print "My program name is : $0 \n";


The output will be :

My program name is : test.pl 


$]

This variable represents the version string that identifies the Perl version that is being run. 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. You can assign a value to the variable, if necessary. When used in a numeric context, it will be equal to the version number plus the patch level divided by 1000.

#!/usr/bin/perl
print "you are using perl version $]\n";
warn "Download the new version!\n" if $] < 5.005;


The output will be :

       Download the new version!
       you are using perl version 5.00402


$!

When used in a numeric context, holds the current value of errno. If used in a string context, will hold the error string associated with errno.

$@

The Perl syntax error message from the last eval command. If null, the last eval was parsed and executed correctly

#!/usr/bin/perl
eval 'print "a malformed perl expression';
print "Error: $@\n";


The output will be:

     Error: Can't find string terminator '"' anywhere before EOF at (eval 1) line 1.



$<

In systems that support users and groups, as well as setting new users and groups within a process, Perl can access both the original and the effective user and group information. This variable holds the real user ID (UID) of the current process.

$>

This variable holds the effective UID of the current process.

$)

This variable holds the read gid of the current process. If the process belongs to multiple groups, then $) will hold a string consisting of the group names separated by spaces.

$(

This real group variable provides access to a list of numbers that represent the real group identifiers (GIDs). If the process belongs to multiple groups, then it gives a space-separated list of groups you are in.

$^T

This variable is the time, in seconds, at which the perl script begins running. (seconds since the start of 1970).

#!/usr/bin/perl
$startime = localtime($^T);
print "This program started at $^T (ie. $startime).\n";


The output will be :

       This program started at 926466098 (ie. Tue May 11 16:41:38 1999). 


$^X

This variable gives the name of the Perl executable used by the script.

#!/usr/bin/perl
print "Name of the Perl executable is: $^X\n";


The output will be :

           Name of the Perl executable is: perl


%ENV

This variable is an associative array that contains entries for your current environment variables. This variable makes it easy to look up a value with the appropriate name. Changing or adding an entry affects only the current process or a child process, never the parent process.

#!/usr/bin/perl
foreach $key (keys(%ENV)) {
printf("%-10.10s: $ENV{$key}\n", $key);
}


The output will be :

  MOZILLA_HO: /usr/lib/netscape
  HOSTTYPE  : i386-linux
  LOGNAME   : joy
  OSTYPE    : linux
  WINDOWID  : 46137357
  SHLVL     : 3
  HOME      : /home/joy
  PWD       : /home/joy/perl
  TERMCAP   : xterm|vs100|xterm terminal emulator (X11R6 Window System):am:km:mi:m
  GROUP     : joy
  PATH      : /usr/sbin:/sbin:/bin:/usr/bin:/usr/local/bin:/usr/bin/X11:/usr/X11R6/bin/usr/local/bin/:/usr/X11R6/bin/usr/local/bin/
  VENDOR    : intel
  HOSTDISPLA: localhost.localdomain:0.0
  DISPLAY   : :0.0
  TERM      : xterm
  SHELL     : /bin/tcsh
  MACHTYPE  : i386
  HOST      : localhost.localdomain
  HOSTNAME  : localhost.localdomain
  USER      : joy


Another Example
#!/usr/bin/perl
$tmp = $ENV{SHELL};
print "The current SHELL is $tmp\n";
     The current SHELL is /bin/tcsh


%SIG







Variables used with reports

$%







$=







$-







$~







$^







$:







$^L







Miscellaneous Variables

$_







$^D







$^I







$^P







$^W







@ARGV







@F







@Inc







%Inc