Friday, August 7, 2009

Special Variables

To know more about special variables see Perl documentation:
C:\>perldoc perlvar

There are some pre-defined in Perl which have special meaning to Perl. They also have some analogous names to them, to use long variable name you need to say in script:
use English;

$_ :
[$ARG]

The default input and pattern-searching space. In following places by default Perl will take $_ as argument. It's a global variable.

* print() and unlink functions.
* pattern matching operations s///, m//, tr/// when used without =~ operator
* default iterator variable in foreach(), if no variable supplied.

@ARGV
It's a array which stores all the command line arguments, with which the Perl program was called.

$(digits):
contains sub pattern matched with corresponding set of capturing parenthesis in last successful pattern match. These all variables are read only and dynamically scoped within the scope of that block.
e.g. m/^(ram:)(\w+ \.)(\d+)/;

In above match $1 will contains"ram:" and $2 contains any alphanumeric character ending with"." and $3 contains and digit character after that.

IO::Handle->input_record_separator(EXPR)
$INPUT_RECORD_SEPARATOR
$RS
$/ : (Global)
It actually splits the input file into records depending upon the value set to it, by default it's newline, so file will be split into lines. This influence Perl's idea of what a "line" is. It should be declared as "local" within any block to make it effective in that block only, otherwise it will remain set till the end of Perl program.

local $/; # Read the whole file in at once
$/ = undef; # Read the whole file in at once
undef $/; # same as above

$/ = ""; # Read in paragraph by paragraph
$/ = "\n%\n"; # Read in Unix fortunes

open(my $fh, "<", $fortunes) or die $!;
while(<$fh>) {
chomp; # remove \n%\n
}
  • We always think that chomp remove newline, it's because $/ is set to newline by default, So changing it's value will also change the way chomp works
  • $/ also changes the way read line(<>) works.
{
local $/ = undef;
open my $fh, "abc.txt" or die $!;
$_ = <$fh>; #whole file is now in $_
}
It is a compile-time error to try and declare a special variable using my.

For more information on Perl's special variables one can refer to any of the following links:

Perl 5 by Example: Using Special variables
Perl Special Variables: chapter 8
Perl In a nutshell: chapter 4
Perl Predefined Names
Perl-Special variables

No comments:

Post a Comment