How to print a variable to a file in Perl?

泪湿孤枕 提交于 2019-12-30 10:00:38

问题


I am using the following code to try to print a variable to file.

my $filename = "test/test.csv";
open FILE, "<$filename";
my $xml = get "http://someurl.com";
print $xml;
print FILE $xml;
close FILE;

So print $xml prints the correct output to the screen. But print FILE $xml doesn't do anything.

Why does the printing to file line not work? Perl seems to often have these things that just don't work...

For the print to file line to work, is it necessary that the file already exists?


回答1:


The < opens a file for reading. Use > to open a file for writing (or >> to append).

It is also worthwhile adding some error handling:

use strict;
use warnings;
use LWP::Simple;

my $filename = "test/test.csv";
open my $fh, ">", $filename or die("Could not open file. $!");
my $xml = get "http://example.com";
print $xml;
print $fh $xml;
close $fh;


来源:https://stackoverflow.com/questions/14318020/how-to-print-a-variable-to-a-file-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!