I am new to Perl, and I used them like this
$_
foreach (@list) {
print "$_\n";
}
@_
sub search {
my ($no, @list) = @_;
}
How exactly do these underscore variables work in Perl? What are the other constructs where they are useful?
I am new to Perl, and I used them like this
$_
foreach (@list) {
print "$_\n";
}
@_
sub search {
my ($no, @list) = @_;
}
How exactly do these underscore variables work in Perl? What are the other constructs where they are useful?
This question always comes up, because it's Perl auto-magic (I made up that term).
foreach (@array_list){
print $_ . "\n";
}
Is equivalent to:
foreach my $item (@array_list){
print $item . "\n";
}
The difference is that when no variable is supplied for the loop, Perl automatically sets the default $_ to provide each item.
Similarly when calling subroutines (or methods - {subroutine in an object}) Perl puts the arguments to the subroutine in the @_ array, since arguments will always be a list.
On the flip side, when a built-in subroutine (or any well-written subroutine) requires arguments and is called with no arguments, it will usually function on $_ or @_ depending on if it's expecting one or many arguments. Some subroutines/methods (AKA functions) may work on either scalar or list values, and they usually default to scalar context and function on $_ by default. Sometimes the name makes it clear that it expects a list (array or hash) and then it defaults to @_ as its input.
Keep in mind, the flip side is talking about subroutine inputs, and their output depends on additional factors. In fact, subroutine outputs usually set $_ or @_ simply by returning a scalar value or list values.
For more on how to write a subroutine that returns values based on context check out wantarray and here's a good breakdown of it: