in reply to handling multiple file handles for code generation

foreach (keys %fhs) { my $fh = $fhs{$_}; if ($_ =~ /\.h\.new$/) { print $fh "#endif\n"; }
The whole point of $_ is that of being the topicalizer: you either want
for my $file (keys %fhs) { # ... print $fh whatever if $file =~ /\.\.new$/; }
or
for (keys %fhs) { # ... print $fh whatever if /\.\.new$/; }
but your mixed form doesn't add to code readability, although -of course- it is not illegal. (I also took the liberty of rewriting the if condition as a statement modifier, as IMHO it is clearer that way.)

Replies are listed 'Best First'.
Re^2: handling multiple file handles for code generation
by danmcb (Monk) on Sep 05, 2005 at 12:16 UTC

    I don't understand your point. AFAIK, $_ is just a variable that happens to have a certain well-known value when used inside a loop like this. Of course, using an explicitly named variable will always aid readability (if it is well named) but there is a balance between brevity and "names that mean something".

    So please clarify - what does "topicalizer" mean, and why does it make what I wrote wriong?

    (But thanks for at least making a comment after downvoting ... ;-)

      So please clarify - what does "topicalizer" mean, and why does it make what I wrote wriong?
      It means it acts much like the pronoun "it", that is, it is the implicit argument of many operators and functions. Thus
      $_ =~ /$regex/;
      is always equivalent to just
      /$regex/;
      but the latter is more concise, and is typically idiomatic of Perl. So it is most often more clear. If (you think) it is not, then an explicit variable name may be in order. And in that case you have to do
      $var =~ /$regex/;
      But then, if you have a bunch of matches (or substitutions or ...) to do, people at times even uses a for loop just for its aliasing effect, e.g.:
      s/$rx1/foo/, s/$rx2/bar/, s/$rx3/baz/ for $var;