Redirecting perl command line to log files
If you want to write a variable $time
to a text file, open
write the file descriptor and print it in your file.
open(my $outfile, '>', 'new.txt');
print $outfile $time;
...
Second, your output redirection should read:
1>>new.txt 2>&1
Which means "add STDOUT (1) to new.txt, redirect STDERR (2) to STDOUT (1)". >>
doesn't make sense for the second part.
Finally, I (and every other programmer perl) is highly recommended for use in your scripts strict
and warnings
pragma. This will help you pick up any bugs or potential problems in your scripts. After you have done this, all variables must be declared with my
, which is a good habit anyway. So after all this, your script should look something like this:
# recommended pragmas:
use strict;
use warnings;
# declare all new variables with "my"
my $cmd="echo hi";
my ($second, $minute, $hour) = localtime();
my $time="$hour:$minute:$second";
# open a writeable filehandle and print to the filehandle
open(my $outfile, '>', 'new.txt');
print $outfile $time,"\n"; # I've added a newline character here so that
# the time and the command output are on different lines ;)
system("$cmd 1>>new.txt 2>&1");
source to share