Here are two examples for your reference.
Record the function running time for any function.
Copy codeThe Code is 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 $ arg1 = shift;
My $ arg2 = shift;
Print "From testFun2 \ n ";
Print $ arg1. "\ n ";
Print $ arg2. "\ n ";
}
My $ log_root = "log" if (! $3 | $3 = "");
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 ";
To call an external command, you must:
Copy codeThe Code is 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;