1

I have a perl script example.pl that I run on linux box. I need to capture the output from the execution of the perl script and timestamp its name. I know the output redirection method but I am looking for a way to do it from the script example.pl itself (if possible)

3 Answers 3

2

It's easy to redirect the STDOUT to a file. Just do this at the beginning of the script:

open STDOUT, '>', "my_stdout_file.txt";

And this is a function that returns a file name with a timestamp:

sub generate_timestamp_filename {
    my $tstamp = sprintf( "%04d%02d%02d%02d%02d%02d", 
                                $now[5]+1900, 
                                $now[4]+1, 
                                $now[3],
                                $now[2],      
                                $now[1],   
                                $now[0] );

    return "my_prefix_$tstamp.txt";
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can redirect output and error streams using Typeglobs or you can do the following.

#!/bin/perl 

open(STDOUT, '>',time.".out") or die $!; #the time function gives you the timestamp
open(STDERR, '>',time.".err") or die $!;
print "output"; #goes to <timestamp>.out
warn "error";   #goes to <timestamp>.err

Comments

0

Here is the quickest way to do this:

 open(STDOUT, ">myfile") or die $!;
 print "Hello world"; #now goes to myfile

 open(STDERR, ">hisfile") or die $!;
 warn "Error here"; #and that's in hisfile

The other alternative is to use select:

open(my $FILE, ">stdout") or die $!;
my $old = select($FILE);

# Done capturing output
select $old;

1 Comment

select will fail if someone uses STDOUT directly and won't be inherited by child processes, but it's easy to restore.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.