$data = q[
smith blue apple cat
jones red grape dog
clark green banana mouse
];
$input = 'Fruit';
@headings= qw(Name Color Fruit Animal);
$counter=0;
for $item (@headings) {
if ("$item " eq "$input ") { $whichColumn=$counter; last;}
$counter++;
}
@data = split("\n",$data);
for $item (@data) {
@columns = split (' ',$item);
print "$columns[$whichColumn]<p>";
}
<untested>
use List::MoreUtils qw[firstidx];$data = q[
smith blue apple cat
jones red grape dog
clark green banana mouse
];
$input = 'Fruit';
@headings= qw(Name Color Fruit Animal);
$whichColumn = firstidx{$_ eq $input}@headings;
@data = split("\n",$data);
for $item (@data) {
@columns = split (' ',$item);
print "$columns[$whichColumn]<p>";
}
</untested>
my $data = q[
smith blue apple cat
jones red grape dog
clark green banana mouse
];
# remove leading and trailing spaces in lines
$data =~ s/^\s+//gm;
$data =~ s/\s+$//gm;
my $input = 'Fruit';
my @headings= qw(Name Color Fruit Animal);
for my $i (0..$#headings) {
next if ($headings[$i] ne $input);
print map {(split(/\s+/))[$i]."\n"}
map {split(/\n/)} $data;
last;
}
As for why I wouldn't use a hash, the real table has 166 columns and 100 rows. And there are about a dozen different tables. I want to be able to just dump these space-delimited tables into my code, without having to write yet more code to extract the columns, in order to have code that prints the columns based on the user's input.
Anyway, from your examples it looks like I wasn't too far off the mark -- Perl just doesn't seem to have a super-efficient way to refer to the Nth word of a line. I guess I'm spoiled by Xtalk, where you can write code like "put word 5 of line 3 of theVar into word 2 of line 6 of someOthervar".