in reply to Adding a column to a file where i took out two columns

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

Replies are listed 'Best First'.
Re^2: Adding a column to a file where i took out two columns
by coolda (Novice) on Sep 24, 2014 at 13:50 UTC
    thanks for the reply, however the out put i want is :
    col1 col3 col3 1 7 77 2 8 88 3 9 99
    I want the col3 side by side

      Ok, that changes things somewhat. How about this:

      #!/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 open my $fIn, '<', \$str1; my $index = 0; my %fileCols = map{+"file1 $_" => $index++} split /\s+/, <$fIn>; my @file1Data; push @file1Data, [split /\s+/] while <$fIn>; close $fIn; my @wantedCols = ('col1', 'col3', 'file1 col3'); open $fIn, '<', \$str2; $index = @{$file1Data[0]}; $fileCols{$_} = $index++ for split /\s+/, <$fIn>; my @slice = map{exists $fileCols{$_} ? $fileCols{$_} : ()} @wantedCols +; print join(' ', map{(split /\s+/)[-1]} @wantedCols), "\n"; while (<$fIn>) { chomp; print join (' ', (@{$file1Data[$. - 2]}, split /\s+/)[@slice]), "\ +n"; }

      Prints:

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

      Note that effectively all of the first file is read into memory to avoid having to re-read and parse it for each following file. This is fine so long as the first file is less than about half the memory you have available.

      Perl is the programming world's equivalent of English