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?
To improve legibility, Perl allows you to use an underscore character instead. The underscore only works within literal numbers specified in your program, not in strings functioning as numbers or in data read from somewhere else. Similarly, the leading 0x for hex and 0 for octal work only for literals.
The arrow operator ( -> ) is an infix operator that dereferences a variable or a method from an object or a class. The operator has associativity that runs from left to right. This means that the operation is executed from left to right.
shift() function in Perl returns the first value in an array, removing it and shifting the elements of the array list to the left by one. Shift operation removes the value like pop but is taken from the start of the array instead of the end as in pop.
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 built-in 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.
Those are special variables in Perl. Refer to Perl - Special Variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With