Issues writing to a file in Perl
I am running this script on solaris. I am trying to write the real, user, and system times to a file, each on a separate line. However, this code instead writes them out together on the same line with a bunch of unknown character开发者_StackOverflow社区 boxes. How can I get each of the times on their own separate line?
#!/usr/local/bin/perl -w
use strict;
use warnings;
my $command = "time echo 'hi' 2>&1 | tee -a runtimes.log";
system ($command);
You'll probably get better results as well as more maintainable code if you use perl code (either times
or POSIX::times
) for getting the system/user times.
$command="ls -lR";
@before{real,user,system,chuser,chsystem}=(time(),times());
system $command;
@after{real,user,system,chuser,chsystem}=(time(),times());
print "real @{[ $after{real}-$before{real} ]}\n";
print "user @{[ $after{chuser}-$before{chuser} ]}\n";
print "sys @{[ $after{chsystem}-$before{chsystem} ]}\n";
or the POSIX version:
use POSIX qw(times sysconf);
$clocks_per_second=POSIX::sysconf( &POSIX::_SC_CLK_TCK );
$command="ls -lR";
@before{real,user,system,chuser,chsystem}=(POSIX::times());
system $command;
@after{real,user,system,chuser,chsystem}=(POSIX::times());
printf "real %2.2f\n", ($after{real}-$before{real})/$clocks_per_second;
printf "user %2.2f\n", ($after{chuser}-$before{chuser})/$clocks_per_second;
printf "sys %2.2f\n", ($after{chsystem}-$before{chsystem})/$clocks_per_second;
Solaris standard line delimiter is \n
, so your code seems right. Look also here.
Possibly your problem has to do with the text editor you are using to view the file...
Two things:
- Check the output of both your
open
andsystem
commands. - Print an extra blank line before you close the file.
Try this:
#!/usr/bin/env perl
use strict;
use warnings; #No need for -w when using this
my $command = "time ls 2>&1 | tee -a runtimes.log";
open (FILE, '>>runtimes.log')
or die qq(Can't open "runtimes.log for writing\n);
my $error = system ($command);
if ($error) {
die qq(Error in executing command "$command": $?\n);
}
print "\n";
close FILE;
exit 0;
精彩评论