First one quick note:
my $file = "file"; # why not... my $temp = "temp"; # makes sense if you later want to use # some other basename for your sequence of files foreach (1..5){ open $file, '>', "$temp$_"; # you just turned $file from a string in +to a filehandle... ... }
In other words your assignment in the first line does nothing since the value gets clobbered when you use open
On to your question. I quickly glanced at the node and the author is basically saying that sometimes it is unclear what $_ is supposed to represent. Whether or not this is the case depends on the context that you use it in. For instance:
It's fairly obvious that each operation of the loop is performed on each line in @lines. However, this may not be the case if you have a longer, more complex loop, and will not work at all if you have nested loops:foreach (@lines) { $_ = uc; # ALL CAPS WOOOOOO s/$/!!!/; # EVERY LINE IS AN EXCLAMATION!!! print; }
There are also times where I will take advantage of $_ to perform a bunch of operations on a single variable in a sort of pseudo-loop:my @timesTable; foreach my $row (0..12) { # foreach my $col (0..12) { @timesTable[$row][$col] = $row * $col; } }
You didn't hear it from me, but the best part about Perl is that once you understand how the lingo works, you can use it any way you damn please. Unless you work with people who won't understand what you're saying, and you want them to understand what you're saying. Then you have turn to these annoying things called "Best Practices".for ($leetString) { # "loops" only once s/very/uber/g; tr/astloe/457103/; s!w!\\/\\/!g; }
In reply to Re: foreach loop and creating files with "$_"
by xyzzy
in thread foreach loop and creating files with "$_"
by james28909
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |