note
pjf
<p>G'day Tito1981,
</p><p>
Under both Windows and Unix-flavoured you can redirect the output of any command to a file using the <tt>></tt> redirection operator, like this:
</p>
<blockquote><tt>
perl myprogram.pl > myfile.xml
</tt></blockquote>
<p>
If you wish to have Perl create and print to a file without using a shell redirect, you can first open a file:
</p>
<code>
my $out_fh;
open($out_fh, ">", "myfile.xml") or die "Cannot open myfile.xml - $!";
</code>
<p>
Once your file is open, you can just use regular print to direct output to it. Note that the filehandle. Note that there is no comma in between the filehandle (which we've placed in <tt>$out_fh</tt>) and the data to be printed. This is known as an <i>indirect argument</i>.
</p>
<code>
print {$out_fh} "<greeting>Hello World!</greeting>\n";
</code>
<p>
The above code is pretty much the same for opening and writing to any file.
</p><p>
If your program is already large, and you don't wish to modify all your existing print statements, then you <i>can</i> re-open STDOUT to a file:
</p>
<code>
open(STDOUT,">","myfile.xml") or die "Cannot redirect STDOUT to myfile.xml - $!";
</code>
<p>
You should be very careful in redirecting STDOUT. Any future maintainer (that's you in six months time) may not expect this to occur, and have a much harder time debugging as a result.
</p><p>
All the very best,
</p>
<!-- Node text goes above. Div tags should contain sig only -->
<div class="pmsig"><div class="pmsig-116014">
<i>Paul Fenwick</i><br>
<a href="http://perltraining.com.au/">Perl Training Australia</a>
</div></div>
495651
495651