- Perl ›
- Predefined variable ›
- here
Default variable $_
There is a default variable in Perl.
$_
Let's first look at some examples where default variable are used.
grep function
Each element of the array passed to grep function is assigned to the default variable.
my @values2 = grep {$_ eq 'cat'} @values1;
"$_" Is the default variable, and each element of @values1 is assigned in order.
This is easy to understand if you think of it as expressing the English pronoun "it".
map function
Each element of the array passed to map function is assigned to the default variable.
my @values2 = map {lc $_} @values1;
When the declaration of a lexical variable is omitted in for
If for omits the declaration of a lexical variable, each element of the array is assigned to the default variable.
for (@values) { print "$_\n"; }
Postfix for
If you use the trailing for, each element of the array is assigned to the default variable.
print "$_\n" for @values;
When the diamond operator is used alone in while statement
while statement Diamond operator < If you use/a> alone, each line is assigned to the default argument in turn.
while (<>) { print "$_\n"; }
This usage above is the usage of default variable that you often see.
Implicit arguments in builtin functions
Some Perl builtin functions use default variable as implicit arguments if you omit the arguments.
This is a bad way to avoid writing it yourself, as it will reduce readability.
For example, if you omit the argument in lc function, the default variable becomes the implicit argument.
my @values2 = map {lc} @values1;
This has the same meaning as if you explicitly wrote the default arguments.
my @values2 = map {lc $_} @values1;
If the argument is omitted in the builtin functions, suspect that an implicit argument is being used.
Implicit target in regular expression
If the left side of regular expression pattern matching operator is omitted, the default variable will be used.
for (@values) { s/cat/dog/; }
This has the same meaning as if you explicitly wrote the default variable.
for (@values) { $_ =~ s/cat/dog/; }