http://www.perlmonks.org?node_id=893244


in reply to cut columns with an array slice

This is where showing sample data is really important if you want people to be able to help you. I am going to make some guesses about your data files and attempt to answer your question.

First, I think your columns file looks like this:

1 3 4 6

If that's the case, then you are forgetting to split the columns data.

In any case, you are doing something strange when you access the data array in your while loop.

!/usr/bin/perl use strict; use warnings; my $col_file = shift; my $data_file = shift; open my $columns, '<', $col_file or die "Could not open $col_file - $!\n"; open my $file, '<', $col_file or die "Could not open $data_file - $!\n"); my @columns = split /\s+/, <$columns>; chomp(@columns); # use a hash for quick lookup of columns to skip # here I use a hash slice to assign undef values to the keys stored in + @columns my %skip; @skip{@columns} = (); while( my $line = <$file>) { chomp $line; my @raw_data = split /\s+/, $line; # Map and grep are a bit tough for newbies but they are important, + powerful tools that should be mastered. # Read from right to left: # Take the list of indexes in @raw_data # (grep) keep only those that do not exist as keys to %skip # (map) and look up the the item at that index in @raw_data # and finally print the resulting list. print join ' ', map $raw_data[$_], grep !exists $skip{$_}, 0..$#raw_data; print "\n"; }

Accessing a negative array index indexes from the end of the array.

Negating an array, causes the array to be evaluated in scalar context, yielding the number of members in the array. This value is then negated. So if @columns has 6 members, then -@columns is -6.

Finally, a few points.