Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help - redirect screen output into a open file handle/logfile

Status
Not open for further replies.

netrookie

Technical User
Jul 6, 2003
29
0
0
US
I am trying to capture output that I need, thus creating my own logfile after script execution. I am using the system() command to execute (2) programs.

The first one is calling another perl script, the second one is a simple printout of the environment, using 'env', but I want it to be appended to the logfile I am creating rather than going to standard out.

Here is my working code:
#!/usr/local/bin/perl -w

use warnings;
use strict;

#Call the main perl script
my $runrc = "./getinfo.pl";
my $chkenv = "/bin/env";

#Run the command
open (MYLOG, ">>/home/mylog") || die "cannot append $!";
my $rc = system ($runrc); #runs the command
if ($rc == 0)
{
print MYLOG "system call worked \n";
}
elsif ($rc == -1)
{
print MYLOG "could not even start the program.:$!\n";
}
else
{
my $exit_signal = $rc & 0x7f;
my $has_coredump = $rc & 0x80;
my $exit_value = $rc >> 8;
}
my $rc2 = system ($chkenv); #runs the command
if ($rc2 == 0)
{
print MYLOG "system call ENV worked: \n";
print MYLOG "$rc2\n";
}
elsif ($rc2 == -1)
{
print MYLOG "could not even start the program.:$!\n";
}
else
{
my $exit_signal = $rc2 & 0x7f;
my $has_coredump = $rc2 & 0x80;
my $exit_value = $rc2 >> 8;
}
close (MYLOG);
 
This seems to work, as I think I understand this correctly:


my $chkenv = `/bin/env`;


Then within, the open handle and a successful check, printed it out to the filehandle.


open (MYLOG, ">>/home/mylog") || die "cannot append $!";
my $rc = system ($runrc); #runs the command
if ($rc == 0)
{
print MYLOG "system call worked \n";
print MYLOG "$chkenv\n";
}


It worked. Is this a good way to do this?
 
Is there any reason why you're not just getting from the built- in %ENV hash rather than calling an external utility?

Code:
foreach my $k (keys %ENV) { print MYLOG "$k=$ENV{$k}\n" };

Annihilannic.
 
Thank you Annihilannic! That's much shorter code. No, I didn't realize I can just call this. I'm still learning a lot on how to use perl. Thanks for the tip.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top