#!/usr/bin/perl use strict; use warnings; use diagnostics; BEGIN { my (@records, @report); my $data_file = 'test.dat'; { open my $fh, $data_file or die "Can't open $data_file: $!"; while (<$fh>) { # skip blank and commented lines next if /^\s*#/; next if /^\s*$/; chomp; # We'll look for lines that describe a report: if (/report:\s+sort\s+(\S*)/ ) { @report = split /,/, $1; } else { push @records, [split /,/]; } } } my %field = ( source => 0, time => 1, sip => 2, sport => 3, dip => 4, dport => 5, hits => 6, acl => 7, lnum => 8 ); my (@sort_sub, @sort_description); # Here is where we do the sub building foreach (@report) { my ($name, $order) = split /-/; my $cmp = $name eq 'source' ? 'cmp' : '<=>'; if ($order eq 'd') { push @sort_sub, qq|\@\$::b[$field{$name}] $cmp \@\$::a[$field{$name}]|; push @sort_description, |$name:\t\tdescending|; } else { push @sort_sub, qq|\@\$::a[$field{$name}] $cmp \@\$::b[$field{$name}]|; push @sort_description, |$name:\t\tascending|; } } my $sort_sub = join "\n\t\t\t || \n\t", @sort_sub; # This is the part I wish to find a better solution for # And here is where we create sort.pl { my $file_name = 'sort.pl'; open my $fh2, '>', $file_name or die "Cannot open $file_name for write: $!"; print $fh2 qq|sub column_sort {\n|, qq|\t$sort_sub;|, qq|\n}\n1;\n|; } sub records { return @records; } sub sort_description { return join "\n", @sort_description; } } require 'sort.pl'; # created with BEGIN my $date = localtime; $date =~ s/ /-/g; ### store report data in file # changed from "$date.txt" to conform to winblows my $report_file_name = 'out.txt'; open my $fh, '>', $report_file_name or die "Can't Open $report_file_name: $!"; print $fh qq|\t\tREQUEST FOR SORTING\n\n|, sort_description, "\n\n", qq|FILE WAS GENERATED ON: $date \n\n|; print $fh (join ',', @$_), "\n" for sort column_sort records; __END__