At 10:21 AM -0230 4/9/12, Tiago Hori wrote:
Sorry guys,
Another quick question:
I got this from perlmonks:
#!/usr/bin/perl -w use strict; my @desired_cols = qw(colname1 colname3);
#order matters here # reads first line to get actual column names my
$header_line = (<DATA>); my @actual_cols = split(/\s+/,$header_line); # get
column number of the actual column names my $pos =0; my %col2_num = map {$_
=> $pos++}@actual_cols; # translate the desired col names into position
numbers my @slice = map{$col2_num{$_}}@desired_cols; print
join("\t",@desired_cols),"\n"; #header line while (<DATA>) { my @row =
(split)[@slice]; print join("\t",@row),"\n"; #each data row }
It is working great fro me and I understand almost all of it. The only
thing I don't get is why you have to split the @slice array into the new
@row array inside the while loop instead of using the @slice array. Doesn't
using split on a array creates a list, which is then assigned to an array
and in effect creates a copy of the original array?
The line
my @row =(split)[@slice];
does not split the @slice array because split is enclosed in
parentheses. 'split' by itself with no arguments will split the $_
variable on whitespace. This results in a list, which is then indexed
by @slice, an array of integers. That results in a slice of the list
returned by split, consisting of the desired columns in the line,
which are the stored in the @row array.
.
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/