in reply to perl if condition
First off, a few things you need to do always in your code:
Then there are a few things that will help your PerlMonks nodes:
Ok, now that's out of the way. Here is what may constitute a solution to your problem:
use strict; use warnings; my $conditions_txt_file = <<FILESTR; 1 eq 1720 5 eq R FILESTR my $test_txt_file = <<FILESTR; 0,1720,123,123,13,123 0,1720,123,123,13,R 0,465,123,123,13,123 FILESTR my @conditions; open my $c_card, '<', \$conditions_txt_file or die "Can't open conditi +ons file: $!\n"; while (<$c_card>) { chomp; next if ! length; push @conditions, [split ' ']; } close $c_card; open my $testHandle, '<', \$test_txt_file or die "Can't open data nfil +e: $!\n"; while (<$testHandle>) { chomp; next if ! length; my @columns = split ','; next if grep {! match ($_, @columns)} @conditions; print join (',', @columns), "\n"; } close $testHandle; sub match { my ($cond, @columns) = @_; my ($column, $test, $value) = @$cond; if ($test eq 'eq') { return if $column < 0 || $column >= @columns; my $match = $columns[$column] eq $value; return $match; } else { die "Don't know how to perform '$test' test\n"; } }
Prints:
0,1720,123,123,13,R
The 'tricky' matching stuff is tucked away in a subroutine that is called within a grep that applies each test to the line being checked and returns a count of failed tests. If none failed they must all have succeeded and the line gets printed. If the number of conditions is huge there may be an advantage in using an explicit loop rather than using grep, but for most purposes grep is likely to be much easier to understand and plenty fast enough.
|
|---|