ck346 has asked for the wisdom of the Perl Monks concerning the following question:

I'm new to perl and have this small perl script I made and I need to change it from displaying the result on the terminal window to outputting it to a file for example like demo.txt instead. I have spent all day and can't figure it out. Any help would be greatly appreciated.

#!/usr/bin/perl -w print "Content-type: text/html\n\n"; foreach my $key (sort keys %ENV) { print "\$ENV{$key} = $ENV{$key}<br/>\n"; } exit;

Replies are listed 'Best First'.
Re: Perl Script help please
by Athanasius (Archbishop) on Oct 05, 2015 at 03:08 UTC

    Hello ck346, and welcome to the Monastery!

    First,

    Now to the question of printing to a file. Do this in three stages:

    1. Open the file for writing. Use the 3-argument form of open together with a lexical (my) filehandle, and check for errors:

      my $output_file = 'demo.txt'; open(my $out_fh, '>', $output_file) or die "Cannot open file '$output_file' for writing: $!";
    2. Print to the filehandle as you would to the console: just put the filehandle as the first argument to open, with no comma between the filehandle and the next argument:

      print $out_fh "\$ENV{$key} = $ENV{$key}\n";
    3. Close the filehandle when you’re finished writing to the output file:

      close $out_fh or die "Cannot close file '$output_file': $!";

    See perlopentut.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: Perl Script help please
by davido (Cardinal) on Oct 05, 2015 at 03:14 UTC

    You can use shell redirection if you like.

    ./myscript.pl > demo.txt

    Or you could modify the script itself:

    #!/usr/bin/perl use strict; use warnings; open my $fh, '>', 'demo.txt' or die $!; print $fh "Content-type: text/html\n\n"; foreach my $key (sort keys %ENV) { print $fh "\$ENV{$key} = $ENV{$key}<br />\n"; } close $fh or die $!;

    I suggest you spend 30 minutes reading perlintro. If this is homework, you're going to need to actually learn this, and perlintro is a good start.


    Dave