in reply to Problem logging STDOUT in perl

Hello kuldeek, and welcome to the Monastery!

I’m not sure exactly what you want, but perhaps the select function is what you’re looking for:

#! perl use strict; use warnings; use autodie; my %test_hash = ( Foo => 1, Bar => 1, Baz => 1, Nix => 0 ); foreach my $test_run (keys %test_hash) { if ($test_hash{$test_run} == 1) { my $test_execute = $test_run; my $test_execute1 = $test_run . '.pm'; my $logfile = $test_execute . '_log.txt'; print "the logfile is $logfile\n"; open(my $out, '>', $logfile); select $out; require $test_execute1; $test_execute->$test_execute(); close($out); select STDOUT; } }

With suitable modules Foo.pm, Bar.pm, and Baz.pm, this code creates a log file for each module and redirects STDOUT to it from that module’s test sub. Output from print "the logfile is $logfile\n" is not redirected.

See how do i redirect STDOUT, STDIN, or STDERR to a FILE?.

Hope that helps,

Athanasius <°(((><contra mundum

Replies are listed 'Best First'.
Re^2: Problem logging STDOUT in perl
by kuldeek (Initiate) on Aug 22, 2012 at 08:34 UTC
    Thanks for the reply. This will redirect logs only to log file, but I need logs to be redirected to log file as well on console i.e. STDOUT.

      Then you should definitely use a module, such as one of those recommended by aitap above:

      #! perl use strict; use warnings; use autodie; use Capture::Tiny qw( tee_stdout ); my %test_hash = ( Foo => 1, Bar => 1, Baz => 1, Nix => 0 ); foreach (keys %test_hash) { if ($test_hash{$_} == 1) { my $logfile = $_ . '_log.txt'; print "the logfile is $logfile\n"; require "$_.pm"; my ($stdout, @result) = tee_stdout { $_->$_() }; open(my $out, '>', $logfile); print $out $stdout; close($out); } }

      ++aitap for recommending Capture::Tiny! I already had it on my system (it came with Strawberry Perl), but I hadn’t come across it before. Brilliant!

      Athanasius <°(((><contra mundum