13. Special variable $_

Perl has several special variables that provide shortcuts and convenience in various situations. Some of the most important ones -often discussed in Part 1- include: $_, $!, @ARGV and @_. In this chapter special attention to $_

$_ is a special default variable to as 'default variable'. It's implicitly used if no other variable is specified. It's widely used in Perl programming, especially in constructs like loops and certain built-in functions. Here's how $_ is typically used:

1. Looping Constructs: $_ is often used in looping constructs like foreach and while when iterating through arrays or filehandles:
@array = qw(Sebastian Daniel Florence);
foreach (@array) {
    print; # $_ represents the current element of @array
}

$str = "Hello!";
for ( split(//, $str) ) {
    # $_ represents the current character
    $ascii_value = ord; # Get the ASCII value of the current character
    print "Character: $_, ASCII Value: $ascii_value\n";# e.g. Character: H, ASCII Value: 72
}

$file = "somefile.txt";
open(FH, '<', $file) or die $!"; # $! holds the error message corresponding to the last system call error.
while () { # read all lines sequentially
  print; # $_ represents the current line from the filehandle $fh
}
close(FH);
Use here the special variable $. to print also the line numbers.

2. Block Constructs: in constructs like map and grep, $_ is used implicitly if no variable is provided:
@array = qw(Sebastian Daniel Florence);
@uppercased = map { uc } @array;
print("@uppercased\n");

@fruits = qw(apple banana cherry grape kiwi);
@apple_fruits = grep { /apple/ } @fruits;
print "@apple_fruits\n";
3. Explicit definition of $_
The explicit definition of $_ is not common. In the next examples however, this demonstrates the function of $_.

3a. Implicit Parameter: many built-in functions in Perl use $_ as an implicit parameter if no explicit parameter is provided. For example, print and chomp:
$_ = "Hello, world!\n";
print; # Output: Hello, world! (with newline)
chomp;
print; # Output: Hello, world! (without newline)
3b. Regular expressions: $_ is used implicitly in regular expressions if no explicit variable is specified. For example:
$_ = "The quick brown fox jumps over the lazy dog";
if (/brown/) {
    print("Matched!");
}
Use here the special variable $& to show the last match.

3c. Unary operators and functions: certain unary operators and functions operate on $_ by default if no explicit operand is provided. For example, uc:
$_ = "hello";
print(uc); # Output: HELLO
Warning!
It's important to note that while $_ is very convenient, it can also lead to confusion in larger programs where it's not immediately clear what $_ is referring to. Hence, it's good practice to use explicit variables when clarity is needed, especially in complex or larger codebases.