In Perl, the special variable ‘$_‘ is called the default or implicit variable. It is used as a default argument or default operand value in a number of functions and operators.
Here are some examples:
1. ‘foreach‘ loop:
The ‘foreach‘ loop is used to iterate over elements in an array or a list. By default, ‘$_‘ is the variable that contains the current element in the array or list being processed.
my @nums = (1, 2, 3, 4, 5);
foreach (@nums) {
print $_, "n"; # prints each number in the @nums array
}
Output:
1
2
3
4
5
2. ‘grep‘ function:
The ‘grep‘ function is used to filter out elements from an array or a list based on a condition. In this case, ‘$_‘ is used as the current element being processed.
my @nums = (1, 4, 6, 7, 9);
my @even_nums = grep { $_ % 2 == 0 } @nums; # filters even numbers from @nums array
print join(" ", @even_nums), "n"; # prints "4 6"
3. ‘s///‘ operator:
The ‘s///‘ operator is used for performing regular expression substitutions. In this case, ‘$_‘ is used as the default scalar variable that contains the string to be replaced.
my $string = "hello world";
$string =~ s/world/Perl Programming/; # replaces 'world' with 'Perl Programming'
print $string, "n"; # prints "hello Perl Programming"
The ‘@_‘ variable is another Perl special variable that is used to store the arguments passed to a subroutine. It is an array variable that stores the list of arguments passed, and can be accessed like any other array.
Here is an example:
sub add_numbers {
my $total = 0;
foreach my $num (@_) {
$total += $num;
}
return $total;
}
my $result = add_numbers(4, 6, 8, 10); # pass a list of numbers as input
print $result, "n"; # prints "28"
In the above example, the ‘add_numbers‘ subroutine takes a list of numbers as input and calculates their sum by iterating over the elements in the ‘@_‘ array. Finally, it returns the total sum.