in reply to get array number

So you want to lookup the field number given the field name? Hashes are usually great as lookup tables. You can use $. to determine whether this is the first line of the file or not (or you could create a flag).

use strict; use warnings; my %col_idx; open(my $result_fh, '<', 'file') # 3-arg safer or die("Unable to open input file: $!\n"); # $! meaningful while (<$result_fh>) { chomp(); # chomp safer my @fields = split(/;/, $_); if ($. == 1) { @col_idx{@fields} = 0..$#fields; } else { # Do what you want here. print "$fields[$col_idx{name}], "; print "$fields[$col_idx{postcode}]\n"; } }

Replies are listed 'Best First'.
Re^2: get array number
by ikegami (Patriarch) on Jan 20, 2006 at 16:20 UTC
    The following is a slightly different version that will allow you to simply type just the field name instead of $col_idx{XXX}:
    use strict; use warnings; my @col_names; open(my $result_fh, '<', 'file') # 3-arg safer or die("Unable to open input file: $!\n"); # $! meaningful while (<$result_fh>) { chomp(); # chomp safer my @fields = split(/;/, $_); if ($. == 1) { @col_names = @fields; } else { my %fields; @fields{@col_names} = @fields; # Do what you want here. print "$fields{name}, "; print "$fields{postcode}\n"; } }

    Untested.

Re^2: get array number
by Fletch (Bishop) on Jan 20, 2006 at 14:16 UTC

    Or just read the first line and parse the headers outside your while loop and avoid the extra logic inside (of course the truly paranoid would then want to error check and make sure that first read didn't return undef . . . :).