Default variable $_ in Perl

All variables in the Perl programming language which contain a single value start with the dollar $. For example, you can create a variable $str or $var.

In Perl there is a special variable $_. There are many places in programming language Perl where if you do not explicitly specify a variable, the variable will be used $_. There are key words that read the values from this variable, and there are those which set of values in this variable. But in this variable save the value on their own.

Keywords that read the value from $_

As an example, a keyword that reads the value of the default variable lead print. If you specify print without arguments, the screen will print the contents of a variable $_.

▶ Run
#!/usr/bin/perl

use strict;
use warnings;

$_ = 'Hello';

print;

First, we saved in a variable $_ line 'Hello' (note we have not used the key word my).

And then we use print, but not send it any arguments. In this use print displays the contents of a variable $_. print; is the same as print $_;

The result — the program will display the text Hello.

Keywords print, say when used without arguments is used default variable $_. It is interesting that the key word warn when using with no arguments variable $_ do not use.

Another example when using the default variable is a regular expression. In order to apply a regular expression to a variable you need to write $str =~ /.../. And if you just write /.../, it is the same as $_ =~ /.../.

Here is a small code example:

▶ Run
#!/usr/bin/perl

use strict;
use warnings;

$_ = 'Hello';

if (/ll/) {
    print 'yes';
} else {
    print 'no';
}

Condition if (/ll/) { check whether the variable $_ two letters l in a row. Because in line'Hello' there are these two letters, then the code runs print 'yes';, which displays the text yes on the screen.

Keywords that put value in $_

The most frequently used key word that changes the value of the variable $_ is foreach. Here is an example code:

▶ Run
#!/usr/bin/perl

use strict;
use warnings;
use feature qw(say);

foreach ('one', 'two', 'three') {
    say;
}

Here the body of the loop foreach is performed 3 times for each item from the list 'one', 'two', 'three'. Before each execution of the loop body in the variable $_ is placed next element from the list. So you can record this cycle with a clear indication of what value should be placed in a variable $_: foreach $_ ('one', 'two', 'three') {

And then we use say; which is the same as say $_;.

Another way to place a value into a variable $_ is to use while (<>) {. Here is the code:

#!/usr/bin/perl

while (<>) {
    print " * $_";
}

This code reads STDIN and outputs each line as a markdown list. Here is an example of how to work with this code in the console:

$ perl -e 'print "1\n2\n3\n"' | perl script.pl
 * 1
 * 2
 * 3

First, we used perl odnotrahniki, which displays three lines, each line figure. And then we have redirected this output to the input of a script that we just wrote. The body of the loop while (<>) { is performed for each line of input, and this string is placed in the variable $_.

Example

Here's another example of code which is actively used default variable $_:

▶ Run
#!/usr/bin/perl

use Data::Dumper;

my @arr = map { ucfirst } grep { /^.{3}\z/ } ('one', 'two', 'three');

print Dumper \@arr;

If you run this program, it will appear on the screen:

$VAR1 = [
          'One',
          'Two'
        ];

So, what's going on here. Expression in which there is an assignment of values to the array @arr you need to read from right to left.

  • First, we identified a list of three strings ('one', 'two', 'three')
  • Then, we used keyword grep to this list. grep places each element from the original list to a variable $_ and checks, which is written in curly brackets. If this test returns true, then grep returns the value of the list. In this example, the curly brackets contain a regular expression that is applied to the default variable. This regular expression will satisfy only strings that consist of exactly three characters. The result of grep is a list of two strings ('one', 'two').
  • A list of two elements fall into map. This keyword puts each list item in default variable and executes the code that is written in curly brackets. The result which returns code is a list item that returns map. In this example we use the function lcfirst, which returns a string whose first character is capitalized. If this function do not specify an argument, then it works with the default variable.

Official documentation

Here's a snippet of the output perldoc perlvar Pro variable $_:

    $_      The default input and pattern-searching space. The following
            pairs are equivalent:

                while (<>) {...}    # equivalent only in while!
                while (defined($_ = <>)) {...}

                /^Subject:/
                $_ =~ /^Subject:/

                tr/a-z/A-Z/
                $_ =~ tr/a-z/A-Z/

                chomp
                chomp($_)

            Here are the places where Perl will assume $_ even if you don't
            use it:

            *  The following functions use $_ as a default argument:

               abs, alarm, chomp, chop, chr, chroot, cos, defined, eval,
               evalbytes, exp, fc, glob, hex, int, lc, lcfirst, length, log,
               lstat, mkdir, oct, ord, pos, print, printf, quotemeta,
               readlink, readpipe, ref, require, reverse (in scalar context
               only), rmdir, say, sin, split (for its second argument),
               sqrt, stat, study, uc, ucfirst, unlink, unpack.

            *  All file tests ("-f", "-d") except for "-t", which defaults
               to STDIN. See "-X" in perlfunc

            *  The pattern matching operations "m//", "s///" and "tr///"
               (aka "y///") 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 implicit variable of "given()".

            *  The default place to put the next value or input record when
               a "", "readline", "readdir" or "each" operation's result
               is tested by itself as the sole criterion of a "while" test.
               Outside a "while" test, this will not happen.

            $_ is a global variable.

            However, between perl v5.10.0 and v5.24.0, it could be used
            lexically by writing "my $_". Making $_ refer to the global $_
            in the same scope was then possible with "our $_". This
            experimental feature was removed and is now a fatal error, but
            you may encounter it in older code.

            Mnemonic: underline is understood in certain operations.

Related topics

Other articles

Comments