#!/usr/bin/perl -w #First example: #Use select to redirect to FILE (which tees to STDOUT) or # to redirect to STDOUT $my_perlhome = "/home/privera/perl"; $log_file = "$my_perlhome/logfile"; $log_file2 = "$my_perlhome/logfile2"; $log_file3 = "$my_perlhome/logfile3"; $log_file4 = "$my_perlhome/logfile4"; $log_file5 = "$my_perlhome/logfile5"; #Flush buffers #$|=1; print "First example: select\n"; open(FILE, "| tee $log_file") or die "Can't open: $!\n"; select (FILE); print "Testing 1.2.3...\n"; close(FILE) or die "Can't close: $!\n"; select (STDOUT); print "done\n"; #Second example: #Uses local (notice braces) print "\nSecond example: local\n"; print "Should go to stdout.\n"; { local *STDOUT; open (STDOUT,"| tee $log_file2") or die "Can't open: $!\n"; print "Should go to second logfile and STDOUT\n"; } print "Should go to stdout.\n"; #Third example: #Uses SelectSaver #Info from perldoc.com: #"A SelectSaver object contains a reference to the file handle that #was selected when it was created. If its new method gets an extra parameter, #then that parameter is selected; otherwise, the selected file handle #remains unchanged. # #When a SelectSaver is destroyed, it re-selects the file handle #that was selected when it was created." print "\nThird example: SelectSaver\n"; use FileHandle; use SelectSaver; { my $newfh = new FileHandle("| tee $log_file3") or die "Can't open: $!\n"; my $saver = new SelectSaver($newfh); # <$newfh> is selected print "Should go to third logfile and STDOUT\n"; } # previous handle (STDOUT) is selected print "Should go to stdout.\n"; print "\nFourth example: select multiple\n"; open(FILE, "| tee $log_file4") or die "Can't open: $!\n"; select (FILE); print "This is written to both STDOUT and the fourth logfile\n"; select (STDOUT); print "This is written only to STDOUT\n"; select (FILE); print "This next message is written to both STDOUT and the fourth logfile\n"; close(FILE) or die "Can't close: $!\n"; select (STDOUT); print "done\n"; print "\nFifth example: select multiple object oriented\n"; my $newfh = new FileHandle ("| tee $log_file5") or die "Can't open: $!\n"; select ($newfh); print "This is written to both STDOUT and the fifth logfile\n"; select (STDOUT); print "This is written only to STDOUT\n"; select ($newfh); print "This next message is written to both STDOUT and the fifth logfile\n"; close($newfh) or die "Can't close: $!\n"; select (STDOUT); print "done\n";