2011-09-22 3 views
5

Log_message 함수를 사용하는 하나의 로그와 OUT에 쓰는 file_write 함수 내에서 하나씩 두 개의 파일에 쓰고 있는데 한 줄 씩 쓰고 버퍼에 넣지 않으려 고합니다. 하나는 대본 끝 부분에 있습니다.

나는 버퍼링에 대해 읽었으며 파일 핸들을 뜨겁게 만들었지 만 작동하도록 코드를 가져올 수 없습니다.

이 예에서는 foreach 루프 바로 전에 $|=1;을 추가했지만 한 번에 씁니다. 내가 정말 바보 같은 짓하고 있니?

도움이된다면 필자의 전체 스크립트를 더 자세히 정리했습니다.

# !c:/Perl/bin/Perl.exe 


#----------------------------------------------- 
#Modules 
#----------------------------------------------- 
use XML::Simple; 
use LWP; 
use Data::Dumper; 
$Data::Dumper::Indent = 1; 
$Data::Dumper::Sortkeys = 1; 
use strict; 
use warnings; 

#----------------------------------------------- 
#Declare variables 
#----------------------------------------------- 
    my $script = "LiveContent Auto Cache Script"; # Name of the script 
    my $version = "Version 0.1"; 
    #my $pubId = "COMP-20110922XXXX"; 
    my $pubId = "LiveContentDoc";  
    my $OUT = "output.txt"; 
    my $LOG = "cacher-log.log";  # Location of log file 
    my $DATE;             # Date in form 2001-sep-01 
    my $DATENR;            # Date in form 2001-01-09 
    my $TIME;            # Time in form 12:04:03 
    my $txtmesg = ""; 
    my $resource; 
    my $xs; 
    my $doc; 

#################################### 
########### Main Program ########### 
#################################### 
error_logger();        # Open Log file and time stamp it 
request_url(); #Open the xml url and read it in 
file_write(); #write the contents of the xml url to a file 


#----------------------------------------------- 
sub request_url { 
#----------------------------------------------- 
my $useragent = LWP::UserAgent->new; 
my $request = HTTP::Request->new(GET => "http://digitalessence.net/resource.xml"); 
#my $request = HTTP::Request->new(GET => "http://dronlineservices.letterpart.com/web/content.xql?action=index&lang=en&pub=" . $pubId); 
$resource = $useragent->request($request); 
$xs   = XML::Simple->new(); 
$doc  = $xs->XMLin($resource->content); 

} 


#----------------------------------------------- 
sub file_write { 
#----------------------------------------------- 
open OUT, ">>$OUT" or Log_message ("\n$DATE - $TIME - ERROR - Could not create filelist.doc \t"); 
Log_message ("\n$DATE - $TIME - INFO - Opened the output file"); 
my $total = scalar keys %{ $doc->{ resource } }; 
Log_message ("\n$DATE - $TIME - INFO - Found: " . $total . " resources"); 
#printf "resources: %s\n", scalar keys %{ $doc->{ resource } }; 



use IO::Handle; 
STDOUT->autoflush(1); 

foreach (keys %{ $doc->{ resource } }) { 
    #print OUT $doc->{ resource }->{ $_ }->{ id }, "\n"; 
    my $ID = $doc->{ resource }->{ $_ }->{ id }, "\n"; 
    Log_message ("\n$DATE - $TIME - INFO - Found: " . $ID); 


    my $testurl = "http://dronlineservices.letterpart.com/web/content.xql?action=doc_html&lang=en&pub=" . $pubId . "&docid=" . $ID; 
    print OUT "$testurl\n"; 


     # my $browser = LWP::UserAgent->new; 
     # $browser->timeout(240); 
     # $browser->env_proxy; 
     # $browser->agent('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'); 

      # my $response = $browser->get($testurl); 

     # if ($response->is_success) { 
      #  print "\n############################\n"; 
      #  print "$testurl\n"; 
      #  print "\n############################\n"; 
       # print $response->decoded_content; # print the response out 
      # } 
      # else { 
      # my $error = $response->status_line; 
      #  Log_message ("\n$DATE - $TIME - WARN - Can't load $ID because: $error"); 
      # die $response->status_line; 

     # } 



    #my $loadrequest = $ua->get('http://dronlineservices.letterpart.com/web/content.xql?action=doc_html&lang=en&pub=" . $pubId . "&docid=" . $ID'); 
    sleep 1; 

} 


Log_message ("\n$DATE - $TIME - INFO - Written the output file"); 
#close(OUT) or Log_message ("\n$DATE - $TIME - WARN - Failed to close the Output file"); 
Log_message ("\n$DATE - $TIME - INFO - Closed the output file"); 
} 
#----------------------------------------------- 
sub error_logger { 
#----------------------------------------------- 
    time_stamp();                                # Run Time stamp sub 
    open LOG, ">>$LOG" or die ("could not open log file <$LOG>");        # Open Log File 
    Log_message ("\n$DATE - $TIME - -----------------------------------------\ \t"); 
     Log_message ("\n$DATE - $TIME - INFO - Start of Application\ \t"); 
     Log_message ("\n$DATE - $TIME - INFO - $script\ \t"); 
     Log_message ("\n$DATE - $TIME - INFO - $version\ \t"); 
     Log_message ("\n$DATE - $TIME - -----------------------------------------\ \t"); 

} 
#------------------------------------------------------------- 
sub Log_message { 
#------------------------------------------------------------- 
    time_stamp();     # Run time_stamp every time the log is written to 
    my($mesg) = @_; 
    print LOG $mesg if $LOG; # Print to log file 
    print $mesg;    # Print to Screen 
    $txtmesg = $mesg; 
    #print "\nLOGGING: $txtmesg\n"; 
} 
#----------------------------------------------- 
sub time_stamp { 
#----------------------------------------------- 
    my($Sec,$Min,$Hour,$Day,$MonthNr,$Year) = localtime(time()); 
    my $Month=("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")[$MonthNr]; 
    $Sec = sprintf("%02d",$Sec); 
    $Min = sprintf("%02d",$Min); 
    $Day = sprintf("%02d",$Day); 
    $MonthNr = sprintf("%02d",++$MonthNr); 
    $Year = 1900 + $Year; 
    $DATE = "$Year-$Month-$Day"; 
    $DATENR = "$Year-$MonthNr-$Day"; 
    $TIME = "$Hour:$Min:$Sec"; 
} # end sub 

답변

16

#----------------------------------------------- 
    sub file_write { 
    #----------------------------------------------- 
    open OUT, ">>$OUT" or Log_message ("\n$DATE - $TIME - ERROR - Could not create filelist.doc \t"); 
    Log_message ("\n$DATE - $TIME - INFO - Opened the output file"); 
    my $total = scalar keys %{ $doc->{ resource } }; 
    Log_message ("\n$DATE - $TIME - INFO - Found: " . $total . " resources"); 
    #printf "resources: %s\n", scalar keys %{ $doc->{ resource } }; 

    $|=1; 

    #And I have also tried: 

    #use IO::Handle; 
    #STDOUT->autoflush(1); 

    foreach (keys %{ $doc->{ resource } }) { 
     #print OUT $doc->{ resource }->{ $_ }->{ id }, "\n"; 
     my $ID = $doc->{ resource }->{ $_ }->{ id }, "\n"; 
     Log_message ("\n$DATE - $TIME - INFO - Found: " . $ID); 
     my $testurl = "http://dronlineservices.letterpart.com/web/content.xql?action=doc_html&lang=en&pub=" . $pubId . "&docid=" . $ID; 
     print OUT "$testurl\n"; 
     sleep 1; 

    } 

그리고 전체 스크립트는 먼저 핸들을 선택하는 것을 잊었다.

select((select(OUT), $| = 1)[0]); 
+4

을, 좋은 읽기는 문서 ('perldoc을 perlvar')입니다 : _ 0이 아닌 값으로 설정하면 현재 선택된 ** 출력 채널에서 모든 쓰기 또는 인쇄 ** 직후 플러시를 강제 실행합니다. _ –

+0

정말 고마워요. 이제 문서를 읽으면 더 잘 이해할 수 있습니다! –

+9

IO :: Handle을 사용하고, OUT-> autoflush (1); 훨씬 더 가독성이 높습니다. –

11
use IO::Handle; 
OUT->autoflush(1); 

하지만 어휘 파일 핸들을 사용하는 것이 좋습니다 : 코드 줄에 대한 몇 가지 설명을 얻기 위해

use IO::Handle; 
open my $outfh, ">>", $OUT or Log_message ("\n$DATE - $TIME - ERROR - Could not create filelist.doc \t"); 
$outfh->autoflush(1); 
+1

게다가'$ | '를 올바르게 사용하는 방법에 대한 질문도있었습니다. 당신의 대답은 그 문제를 해결하지 못합니다. 마지막으로, 당신은 어휘 파일 핸들이라고 말하지만, 당신은 그것을 의미하지는 않습니다. 자동 핸들을 의미합니다. – tchrist

+3

@tchrist, 물론입니다. '$ |'를 사용하는 올바른 방법은'autoflush'를 통해 그것을 사용하지 않는 것입니다. – ikegami

+0

@ikegami "바르게"바보 같다. '$ |'는 더 이상 사용되지 않으며, 아무도 그것을 가장하는 척하지 않습니다. – tchrist

관련 문제