ck346
ck346

Reputation: 13

Perl Script help outputting to file

I have the script below that I need to output to a file, like perl.txt instead of displaying in the terminal window. This is my first time with perl and can't quite get that part if anyone could offer any advice that would be great.

print "Content-type: text/html\n\n";

foreach my $key (sort keys %ENV) {
print "\$ENV{$key} = $ENV{$key}<br/>\n";
}

exit;

Upvotes: 0

Views: 55

Answers (2)

serenesat
serenesat

Reputation: 4709

Here is a tutorial: Writing to files with Perl.

use strict;
use warnings;

# First open a file in write mode
open my $output, '>', 'perl.txt' or die "Can't open file to write: $!";

# use the filehandle with print to write in file instead of printing on terminal
print $output "Content-type: text/html\n\n";

foreach my $key (sort keys %ENV)
{
    print $output "\$ENV{$key} = $ENV{$key}<br/>\n";
}
# close the open file
close $output;

Upvotes: 0

aschepler
aschepler

Reputation: 72463

You need to open the file and pass its file-descriptor to print.

open(my $out, ">", "perl.txt") or die "perl.txt: $!";

print $out "Content-type: text/html\n\n";

foreach my $key (sort keys %ENV) {
    print $out "\$ENV{$key} = $ENV{$key}<br/>\n";
}

close($out) or die "perl.txt: $!";

Note there's no comma after $out in the print statements.

Upvotes: 4

Related Questions