|Perl Monk, Perl Meditation|
Re: On patterns and moreby ELISHEVA (Prior)
|on Mar 06, 2011 at 12:57 UTC||Need Help??|
$_ is a variable that is set to whatever Perl thinks you are most likely to want to use as a default command/subroutine argument. Many Perl commands will automatically use whatever value is assigned to $_ so you don't have to do so much typing:
The actual value assigned to $_ depends on the context because what you are "most likely to want to use as an argument" usually depends on what you are doing in your code at that moment.
In a for loop $_ is the current array element.
If you are reading from a file using the <> operator, it is the most recently read line, e.g.
You don't have to use $_ for loops. In fact, for production code, it is a good idea not to because every so often something you are doing inside the for loop might unexpectedly reset $_ (it shouldn't but you don't always have control over other people's code and how they use things like $_. The inside of loops often makes calls to other people's code). For example, your loop above could also have been written:
The same caution about $_ also applies to $_ when reading from an input stream or any other use of $_. If you are doing something complicated, it is best to assign $_ to a variable with a name you control and to use that variable instead of $_. Thus a better way to write the code reading from STDIN above would be
Update: added comment about non-working code and referenced sherm's explanation below.