See code below... is the current selected filehandle (usually STDOUT, but not in the magic while(<>)) some perl default variable? I looked in perlvar but didn't see anything. How does this inplace edit magic work? Where is it documented?
use strict; use warnings; use Test::More qw(no_plan); #create a.txt contining "a" open F, "> a.txt"; print F "a"; close F; #fails because no substitution was made #prints to STDOUT process_file(); local $^I = ".bak"; #now it works. #prints to "a.txt" as we want. But how does it know to print there? write_and_read_file(); #ok sub process_file { @ARGV = qw(a.txt); local $/; # slurp it #changes a.txt so contains "b" #the diamond operator operates on @ARGV by default while (<>) { #$_ now contains the entire file, alter at will s/a/b/g; #How does the print operator know what file handle to print to +? #Was this selected somewhere by magic? #Where is this documented / explained? print; } #need to reset @ARGV, I guess it got wiped out somewhere in that w +hile. @ARGV = qw(a.txt); while (<>) { is($_,"b"); } }
Outputs:
bnot ok 1 # Failed test (diamond.pl at line 35) # got: 'a' # expected: 'b' Undefined subroutine &main::write_and_read_file called at diamond.pl l +ine 15, <> line 1. 1..1 # Looks like you failed 1 tests of 1. # Looks like your test died just after 1.
(Inspired by Re: Shell trick to edit many files with perl)

In reply to how does print know what filehandle to use, when in a diamond in-place edit loop? by tphyahoo

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.