Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks, I am having problems with a foreach loop. I am reading in a tab-delimited file, and want to split the file on the whitespace (giving three columns), however, when i try and print these columns, only the top value prints, not the whole column. Where am i going wrong?? Cheers!
# @thermo_params contains the data. my @thermos; my $data_line; foreach $data_line (@thermo_params) { @thermos = split (/\s+/, $thermos); print "$thermos[0]\n"; print "$thermos[2]\n" }

Replies are listed 'Best First'.
Re: foreach problem
by dws (Chancellor) on Feb 26, 2003 at 10:10 UTC
    when i try and print these columns, only the top value prints, not the whole column. Where am i going wrong?

    The variable you're splitting appears to be a remnant of some earlier operation. Try changing

    @thermos = split (/\s+/, $thermos);
    to
    @thermos = split (/\s+/, $data_line);
Re: foreach problem
by edan (Curate) on Feb 26, 2003 at 11:00 UTC
    Using
    use strict;

    will help to avoid these kinds of errors.
    Cheers!
Re: foreach problem
by Hofmator (Curate) on Feb 26, 2003 at 13:33 UTC
    Apart from the obvious error caught by dws, I'd recommend keeping the my statements as locally scoped as possible, like this:
    foreach my $data_line (@thermo_params) { my @thermos = split /\s+/, $data_line; print "$_\n" for @thermos[0,2]; }

    -- Hofmator

      Or just:
      local $" = "\n"; print "@{[(split) [0, 2]]}\n" for @thermo_params;

      Abigail