如何在Perl中将变量打印到文件? [英] How to print a variable to a file in Perl?

查看:856
本文介绍了如何在Perl中将变量打印到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码尝试将变量打印到文件中.

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;

因此,print $xml将正确的输出打印到屏幕上.但是print FILE $xml什么也没做.

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

为什么打印到文件行不起作用? Perl似乎经常有这些东西行不通...

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?

推荐答案

<打开一个文件以供读取.使用>打开要写入的文件(或添加>>追加).

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;

这篇关于如何在Perl中将变量打印到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆