Special Variables in PERL - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Special Variables in PERL

Share This

There are some variables which have a predefined and special meaning in Perl. They are the variables that use punctuation characters after the usual variable indicator ($, @, or %), such as $_ ( explained below ).

Most of the special variables have an english like long name, e.g., Operating System Error variable $! can be written as $OS_ERROR. But if you are going to use english like names, then you would have to put one line use English; at the top of your program file. This guides the interpreter to pickup exact meaning of the variable.

The most commonly used special variable is $_, which contains the default input and pattern-searching string. For example, in the following lines -

#!/usr/bin/perl foreach ('hickory','dickory','doc') { print $_; print "\n"; }

Again, let's check the same example without using $_ variable explicitly -


#!/usr/bin/perl foreach ('hickory','dickory','doc') { print; print "\n"; }

The first time the loop is executed, "hickory" is printed. The second time around, "dickory" is printed, and the third time, "doc" is printed. That's because in each iteration of the loop, the current string is placed in $_, and is used by default by print. Here are the places where Perl will assume $_ even if you don't specify it -

Various unary functions, including functions like ord and int, as well as the all file tests (-f, -d) except for -t, which defaults to STDIN.

Various list functions like print and unlink.

The pattern-matching operations m//, s///, and tr/// when used without an =~ operator.

The default iterator variable in a foreach loop if no other variable is supplied.

The implicit iterator variable in the grep and map functions.

The default place to put an input record when a line-input operation's result is tested by itself as the sole criterion of a while test (i.e., ). Note that outside of a while test, this will not happen.




Happy Exploring!

No comments:

Post a Comment