How to print a variable to a file in Perl?

I am using the following code to try to print a variable in a 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 displays the correct result on the screen. But print FILE $xml does nothing.

Why doesn't printing in a file line work? It seems like Perl often has things that just don't work ...

Does the print line need to exist in the file to work?

+4
source share
1 answer

< opens the file for reading. Use > to open the file for writing (or >> to add).

It is also useful to add 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; 
+21
source

All Articles