Lazer Lazer - 7 months ago 21
Perl Question

What is the significance of an underscore in Perl ($_, @_)?

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?

Answer

This is the sort of question which indicates you really should be reading a book, and perhaps the rest of the perl tag faqs.

Nevertheless, $_ is a context variable which is created implicitly by certain constructs and used implicitly by certain builtin functions. Here are some examples:

while(<>) {
    next if /^#/;
    last if /^q(?:uit)?$/;
    say "Howdy!" if /^hello$/;
}

This doing a lot of work setting and inspecting the $_ variable and is equivalent to:

while(defined($_ = <>)) {
    next if $_ =~ /^#/;
    last if $_ =~ /^q(?:uit)?$/;
    say "Howdy!" if $_ =~ /^hello$/;
}

Other constructs which set $_ are: foreach loops, given blocks, map and grep operations, and catch blocks in Try::Tiny.

Other constructs which use $_ are: bare print; statements, the s/// substitution operator and the tr/// transliteration operator.

I'd advise this: while you are learning Perl, don't use $_ implicitly. Write it all out in full (as in the second example above), to reinforce in your mind what is actually going on. Just like when you are learning a foreign language, you should learn to speak properly and carefully before you learn to abbrv y'language. $_ is useful for writing shorter, terser code, and can actually be clearer by focussing on the processing going on rather than the variables it is being done to, but only once you have learned as second nature which operations are using $_. Otherwise it's just a confusing mess.

As mentioned elsewhere, @_ is the argument list to a subroutine.