Array in Perl - Detect several file to be in one array

Hi everyone

I have one question about using array in perl. let say I have several log file in one folder.. example

test1.log
test2.log
test3.log
and the list goes on..

how to make an array for this file? It suppose to detect log file in the current directory and all the log file will be in one array. anyone know?

% touch test{1..5}.log
% ls
test1.log  test2.log  test3.log  test4.log  test5.log
% perl -MData::Dumper -le'
  @a = glob "*.log";
  print Dumper \@a
  '
$VAR1 = [
          'test1.log',
          'test2.log',
          'test3.log',
          'test4.log',
          'test5.log'
        ];

Hi

I have this code

open(MYOUTFILE, "fps.log"); 
open(RESULTFILE, ">result.txt"); 
my $total=0; 
my $lines=0;
while (<MYOUTFILE>) { chomp; my $value = (split /([,:])/)[2]; $total=$value+$total; $lines++; }
print RESULTFILE $total/$lines;

This code is work for one fps.log file only. My program suppose to detect .log file in current directory then it will do the process

while (<MYOUTFILE>) { chomp; my $value = (split /([,:])/)[2]; $total=$value+$total; $lines++; }
print RESULTFILE $total/$lines;

and print the result. Each log file have their own result file. but I fail to make it so

You could use something like this:

#!/usr/bin/perl

use warnings;
use strict;

my @log_files = glob "*.log";
my ($total, $lines);

for my $log_file (@log_files) {

(my $res_file = $log_file) =~ s/\.log$/.res/; 

  open my $log_fh, '<', $log_file
    or warn "open $log_file: $!\n";

  open my $res_fh, '>', $res_file
    or die "open $res_file: $!\n";
  
  $total = $lines = 0;    
    
  while (<$log_fh>) {
    $total += (split /[,:]/)[2];
    ++$lines;
    }   

  print $res_fh $total / $lines, "\n";    
  
  close $log_fh
    or warn "close $log_file: $!\n";
    
  close $res_fh
    or warn "close $res_file: $!\n";
  }

With recent versions of Perl you could use autodie and avoid all that manual exception handling.