On page 49 of "Learning Perl 3rd Ed." there's an example on modifying the control variable inside a foreach loop. Here's the code:
@rocks = qw/ bedrock slate lava /;
foreach $rock (@rocks) {
$rock = "\t$rock";
$rock = "\n";
}
print "The rocks are:\n", @rocks;
I have no problem understanding the above code. It's when I apply to the above code what the book teaches next---> $_ where the question is.
Books says if the foreach control variable $rock is not specified, Perl will use $_ in its place. Okay, fine with me, but when I run a modified version of the above code without the $rock control variable, the printed output displays:
The rocks are:
bedrockslatelava
The foreach line was changed from "foreach $rock (@rocks)" to "foreach (@rocks)".
Seems to me the default $_ work correctly only when you don't have to modify the control variable?
For some other constructs, $_ is the default parameter, so this shorthand saves you some work. But for others, there is not much saving, but it still works correctly.
That can't be it. Hello world prints out hello world. Each line in the code does something which is instructive to the students. In this case blank lines would be printed out instead of the list of rocks each on a new line indented by a tab, and that would just confuse the hell out of students. It must be a typo. Probably in Ray's post; possibly in the text.
The example of modifying the control variable inside a foreach loop is demonstrated on the line above, without the need for the $_ = "\n"; line