#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2008
    Posts
    10
    Rep Power
    0

    Avoid duplicating code in a loop to process zipped and non zipped log files


    Hello All,

    I wrote a script which reads in a loop bzip2 compressed log files using Compress::Bzip2.
    Now I want to expand the script to process also non compressed log files.
    What I NOT want is to duplicate the lengthy code in the loop for non compressed log files.

    Any help is appreciated

    Code:
    use Compress::Bzip2;
    
    if($file =~ /\.bz2$/) {
    	$fh=bzopen($file,"r");
    	$fileIsZipped=1;	
    } else {
    	open($fh,"<",$file);
    	$fileIsZipped=0;
    }
    
    while($fileIsZipped == 1 ? $fh->bzreadline($line) : $line=<$fh>) { # <----- can the erroneous code beside somehow be accomplished?
    	. lots of code
    	. lots of code
    	. lots of code
    }
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Apr 2009
    Posts
    1,921
    Rep Power
    1225
    Code:
    if($file =~ /\.bz2$/) {
    	my $fh = bzopen($file,"r");
            my $line;
    	while ( $fh->bzreadline($line) ) { process_line($line); }
            
    } else {
    	open( my $fh, "<", $file ) or die "failed to open '$file' <$!>";
    	while ( my $line = <$fh> ) { process_line($line); }
    };
    
    
    sub process_line {
        . lots of code
        . lots of code
        . lots of code
    }
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2008
    Posts
    10
    Rep Power
    0
    Thank you FishMonger,

    I implemented it the way you suggested.
    Sometimes I donīt see the forest because of all the wood.

IMN logo majestic logo threadwatch logo seochat tools logo