Hi,

A useful thing for you to know would be that you can supply an optional filehandle argument to the print function if you would like to print to a file. This optional argument, when not present, defaults to STDOUT, which is why all your output has been printing to the screen. Try using something more like this:

my $filename='out.txt'; my $output ='perl_output.txt'; if (-r $filename) { open(FILE, "< $filename"); open(OUTPUT, "> $output"); while(<FILE>) { chomp; if(/^(.*)Datasource:/){ print OUTPUT "\n\n", $_, "\n"; ... ... } close(FILE); close(OUTPUT); } else{ print("cant read file ",$filename,"\n"); }

See, I opened a new file to hold the output, with a ">" to indicate that perl should create it if it isn't there already. The ">" also will make perl clobber that file each time you run the script, so if the output is important, you should save that somewhere else before you run it again.

Later on in the loop, I print to the filehandle by using it as an argument to print. The final print statement has no extra argument, so it defaults to STDOUT and prints the error message to your screen.

Of course, there is a lot more about standard functions like 'print' and 'open' in the perl documentation. On my system, I would use:

perldoc -f print

... if I wanted to know more. Hope this was what you needed!


In reply to Re: simple regex question by mull
in thread simple regex question (parsing and saving a file) by Anonymous Monk

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.