Your problem description, example and code don't seem to be consistent so the following is a guess at what you may be after:

#!/usr/bin/perl use warnings; use strict; my $str1 = <<STR; col1 col2 col3 1 4 7 2 5 8 3 6 9 STR my $str2 = <<STR; col1 col2 col3 1 44 77 2 55 88 3 66 99 STR for my $spec ([$str1, qw(col1 col3)], [$str2, qw(col3)]) { my ($file, @wantedCols) = @$spec; print "@wantedCols\n"; open my $fIn, '<', \$file; my $index = 0; my %fileCols = map{$_ => $index++} split /\s+/, <$fIn>; my @slice = map{exists $fileCols{$_} ? $fileCols{$_} : ()} @wanted +Cols; while (<$fIn>) { chomp; print join (' ', (split /\s+/)[@slice]), "\n"; } }

Prints:

col1 col3 1 7 2 8 3 9 col3 77 88 99

Note the "string as file" trick used to make the sample self contained and printing to stdout (for the same reason) will need to be changed to suit your real application of course. But using a self contained script like this as a test bed can speed up development and testing a lot because you don't need to juggle multiple files during testing.

Note too the three parameter open and the use of lexical file handles. Both things you should get into the habit of using.

Perl is the programming world's equivalent of English

In reply to Re: Adding a column to a file where i took out two columns by GrandFather
in thread Adding a column to a file where i took out two columns by coolda

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.