my @cols = (0, 2); # You would actually get these from @ARGV but it doesn't matter here # ... for my $fieldnum (@cols) { if ( exists $hash{ $fields[$fieldnum] } ) { print $fh "$row\n"; next; } }