Search code examples
perleval

How do I redirect eval output to a file?


I am writing a Perl script where I read files containing section Perl code and non Perl data.

After processing the files I write them to a temporary files (generated scripts) which is then executed using an eval command. I don't want to run the generated script separately as I need to use the variables in the main script to be interpolated in the generated scripts.

I need to redirect the output of the eval command to a file. Any suggestion on how to achieve this?

Steps in the script:

  1. READ_FILE

  2. Process file

  3. Write back with temp file name

  4. Read temp file (my $file_name = read_file('temp_file_name'))

  5. eval (eval $file_name)

Appreciate the help.


Solution

  • This can be done without any additional modules

    use strict;
    use warnings;
    
    open my $fh, '>', 'foo.txt' or die $!;
    my $old_fh = select $fh;
    
    eval q{ print "Hello World!\n"; };
    
    select $old_fh;