Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a variable to a file in 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;

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?

like image 453
user788171 Avatar asked Jan 14 '13 11:01

user788171


People also ask

How do I print a variable value in Perl script?

Printing Perl variables with print In any real-world Perl script you'll need to print the value of your Perl variables. To print a variable as part of a a string, just use the Perl printing syntax as shown in this example: $name = 'Alvin'; print "Hello, world, from $name.

How do I print to a file in Perl?

open(WF,'>','/home/user/Desktop/write1. txt'; $text = "I am writing to this file"; print WF $text; close(WF); print "Done!\ n"; perl.

How do I redirect output to a file in Perl script?

Terminal redirects Before you launch your favourite text editor and start hacking Perl code, you may just need to redirect the program output in the terminal. On UNIX-based systems you can write to a file using “>” and append to a file using “>>”. Both write and append will create the file if it doesn't exist.


1 Answers

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;
like image 130
Quentin Avatar answered Nov 01 '22 07:11

Quentin