Here for you to give two small examples for friends to learn a reference.
Record the time that the function was run on any function.
Copy Code code as follows:
#!/usr/bin/perl
Use warnings;
Use strict;
No strict "refs";
Sub testlogtostd{
Print "Test stdout: \ n";
Open LOG, "> 2.txt";
Select LOG;
Print "Just a test\n";
#recover STDOUT
Select STDOUT;
Print "Just a test2\n";
Close LOG;
}
Sub testfun{
Print "from testfun\n";
Print STDERR "from Testfun error\n";
}
Sub testfun2{
My $arg 1 = shift;
My $arg 2 = shift;
Print "from testfun2\n";
Print $arg 1. " \ n ";
Print $arg 2. " \ n ";
}
My $log _root = "Log" if (! $ | | $ = = "");
My $ret = System ("mkdir $log _root") if (!-e $log _root);
My $report _log = "$log _root/report.log";
Open my $REPORTLOG, ">", $report _log or die "Cannot not open log file report.log\n";
Sub logwrapper{
My $log _root = shift;
my $REPORTLOG = shift;
my $fun = shift;
my @parameters = @_;
*old_stdout = *stdout;
*old_stderr = *stderr;
Open log, ">", "$log _root/$fun. Log" or die "Annot open log file $fun. \ n";
*stdout = *log;
*stderr = *log;
my $start = time;
My $ret = & $fun (@parameters);
my $end = time;
*stdout = *old_stdout;
*stderr = *old_stderr;
Close LOG;
My $duration = $end-$start;
Print $REPORTLOG "$fun \ n";
Print $REPORTLOG "Start:". LocalTime ($start). \ n ";
Print $REPORTLOG "End:". LocalTime ($end). \ n ";
Print $REPORTLOG "duration:". Formattimeduration ($duration). \ n ";
Print $REPORTLOG "Result: $ret \ n";
Print $REPORTLOG "\ n";
Print $REPORTLOG "\ n";
}
Sub Formattimeduration ($) {
my $t = shift;
my $hrs = Int ($t/3600);
my $mins = Int ($t%3600/60);
my $secs = Int ($t%3600%60);
Return "$hrs: $mins: $secs";
}
&logwrapper ($log _root, $REPORTLOG, "Testfun");
&logwrapper ($log _root, $REPORTLOG, "testFun2", "Arg1", "arg2");
print "thanks\n";
If you need to invoke an external command, you need the following:
Copy Code code as follows:
#!/usr/bin/perl
Use strict;
Use warnings;
# Run External commands
# REDIRECT StdOut and stderr
Sub run_cmd{
my $cmd = shift;
My $pid = open (PH, "$cmd 2>&1 |");
while (<PH>) {print $_;}
}
Open (FH, ">", "Perl-test.log");
*old_stdout = *stdout;
*old_stderr = *stderr;
*stdout = *FH;
*stderr = *FH;
my $ret = undef;
$ret = readpipe ("cp a B");
$ret = System ("CP a B");
$ret = ' cp a B ';
Run_cmd ("cp a B");
print "AA";
Print STDERR "BB";
*stdout = *old_stdout;
*stderr = *old_stderr;