guiwp has asked for the wisdom of the Perl Monks concerning the following question:

To use FILEHANDLE alone to print the content of $_ to it, you must use a bareword filehandle like FH, not an indirect one like $fh

I saw some websites saying that BAREWORDS to refer file handles are dangerous because they are global. But now here I see they "prohibiting" it when you like a syntax sugar. Just don't get it...

Is there any other context where automatic use of $_ can't be applyed?

I mean, if I want to print the current $_ to another file handle (not STD{OUT,ERR, etc.) I can't omit $_:

while(<>){ print $fh; #doesn't work print $fh $_; #work }

Replies are listed 'Best First'.
Re: Where automatic variable $_ doesn't work?
by choroba (Cardinal) on Jul 04, 2016 at 19:58 UTC
    You can use select if sugar is so important:
    select $fh; print while <>;

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

      However:

      print $fh while <>;

      is both shorter and clearer.

      Update: Argh! that falls foul of the OP's complaint. It needs to be:

      print $fh $_ while <>;

      to work as intended.

      Premature optimization is the root of all job security
        Although its output is quite different.

        ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

      I didn't known about select, Thank you!

      "if sugar is so important"

      When it's possible, I do like =)

Re: Where automatic variable $_ doesn't work?
by haukex (Archbishop) on Jul 04, 2016 at 20:04 UTC

    Hi guiwp,

    It's not "prohibited": How should Perl tell the difference between print $fh; and print $fh;? With the first one I meant "print the value of $fh to the currently selected filehandle" and with the second one I meant "print $_ to the filehandle $fh"? That's taking DWIM a little too far ;-)

    Regards,
    -- Hauke D

      I always thought Perl was taking DWIM a little too far! I assume the compiler (and the human that made it!) is pretty smart =)

      Thank you @haukex