Open file and Splitting String in Perl

What I gonna do is to read a bunch of data from a file, and perform some data processing from the string.

  • split() is the Perl function which I will use for filtering the data.
  • open for reading a file into array.

I took MRTG’s data log to do some data processing. On the first column of MRTG log file is Unix timestamp, I would like to print the unix Timestamp to human readable date and time, the other columns are traffic in and out in bytes, which I want to find out which traffic is more than certain values.

Below is the sample of MRTG’s log file (mrtg.log), it’s more than 1000 lines


1263954197 4778984843734474 1971197295597596
1263954197 184057628 54266478 184057628 54266478
1263953906 181938506 53715962 181938506 53715962
1263953700 182506581 53937120 182750043 54031903

Perl script will read the log data, split the data by space on each line into array, perform condition compare and find out the date.


#!/opt/local/bin/perl

open FILE, "mrtg.log";
my @logs = \;

foreach my $log (@logs)
{
        my @data = split(' ', $log);
        if ($data[1] > 500000000) {       
            print scalar localtime($data[0]), " ## ", $data[1], " ## ", $data[0], "\n";
        }
}

After going through more than 1000 lines of MRTG log, below is the output


Wed Jan 20 10:23:17 2010 ## 4778984843734474 ## 1263954197
Fri Jan 30 08:00:00 2009 ## 847491342 ## 1233273600
Tue Jan 13 08:00:00 2009 ## 844059530 ## 1231804800

This shows there were traffic spike twice during some where in Jan 2009. That’s split() and open in Perl.