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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |