G'day Tito1981,

Under both Windows and Unix-flavoured you can redirect the output of any command to a file using the > redirection operator, like this:

perl myprogram.pl > myfile.xml

If you wish to have Perl create and print to a file without using a shell redirect, you can first open a file:

my $out_fh; open($out_fh, ">", "myfile.xml") or die "Cannot open myfile.xml - $!";

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 $out_fh) and the data to be printed. This is known as an indirect argument.

print {$out_fh} "<greeting>Hello World!</greeting>\n";

The above code is pretty much the same for opening and writing to any file.

If your program is already large, and you don't wish to modify all your existing print statements, then you can re-open STDOUT to a file:

open(STDOUT,">","myfile.xml") or die "Cannot redirect STDOUT to myfile +.xml - $!";

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.

All the very best,


In reply to Re: Sending output to an xml file by pjf
in thread Sending output to an xml file by tito1981

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.