#!/usr/bin/perl use warnings; use strict; my $str1 = < $index++} split /\s+/, <$fIn>; my @slice = map{exists $fileCols{$_} ? $fileCols{$_} : ()} @wantedCols; while (<$fIn>) { chomp; print join (' ', (split /\s+/)[@slice]), "\n"; } } #### col1 col3 1 7 2 8 3 9 col3 77 88 99