#!/usr/bin/perl use warnings; use strict; die "Usage: $0 filter_file input_file\n" unless @ARGV == 2; my @filters; my %dispatch; for my $op (qw/== != <= >= < > eq ne le ge lt gt/) { $dispatch{$op} = eval qq{ sub { \$_[0] $op \$_[1] } }; } use constant { COLUMN => 0, REL => 1, VAL => 2, TYPE => 3, # Ignored at the moment ACTION => 4 }; open my $DATA, '<', pop or die $!; my @col_names_arr = split ' ', <$DATA>; my %col_names; $col_names{$col_names_arr[$_]} = $_ for 0 .. $#col_names_arr; open my $FILTER, '<', pop or die $!; <$FILTER>; # Skip header line while (<$FILTER>) { my ($column, $rel, $val, $type, $action, $order, $rest) = split; die "Ivalid format at line $.\n" if $rest; die "Duplicate order $order at line $.\n" if $filters[$order - 1]; die "Unknown column $column at line $.\n" unless exists $col_names{$column}; $filters[$order - 1] = [$column, $rel, $val, $type, $action]; } close $FILTER; while (<$DATA>) { my @data = split; FILTER: for my $f (@filters) { my $sub = $dispatch{$f->[REL]}; die "Unknown operator $f->[REL]\n" unless ref $sub; my $result = $sub->($data[$col_names{$f->[COLUMN]}], $f->[VAL]); if ($result) { last FILTER if 'filter' eq $f->[ACTION]; if ('append' eq $f->[ACTION]) { print; } else { die "Unknown action $f->[ACTION]\n"; } } } }