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

Hi, this is my first post so please go easy! I am just learning perl and have what i'm sure is a trivial problem..anyway. All i'm trying to do is split a file into three columns that can be accesible by elements of an array. The problem is that the code below only prints the first value in $file[2]. I really can't see where i'm going wrong. Please help.
#e.g. file looks like; # type value value2 # 503 1093 4395 # 498 2134 9832 # etc....... @file # contains data foreach my $line (@file) { @file = split (/\s+/, $line); } print "$file[2]\n";

Edit: Added <code> tags. larsen

Replies are listed 'Best First'.
Re: problems with split
by integral (Hermit) on Mar 03, 2003 at 18:20 UTC
    The problem with your code is that the print statement is outside of the foreach loop (its outside of the curly braces which define the extent of the loop). To get it to print the second field on each line, this statement should be inside the loop so that it gets called for each line.
    # type value value2 # 503 1093 4395 # load the data @file = <FILE>; # or use a while (defined(my $line = <FILE>)) { loop for my $line (@file) { # for is the same as foreach my @fields = split (/\s+/, $line); # @file was being reused print "$fields[2]\n"; }

    --
    integral, resident of freenode's #perl
    
      can I do this without the filehandles?? cheers ;->
        You have to use a filehandle to read data in from a file, but for a simple program you can get away with using a <> to load data from the files listed in @ARGV (or STDIN if no files are given) with perl automatically opening them as needed.
        while (<>) { print (split /\s+/)[2], "\n"; }

        --
        integral, resident of freenode's #perl
        
Re: problems with split
by dws (Chancellor) on Mar 03, 2003 at 20:27 UTC
    You've got an answer to your problem as stated, but there's another problem lurking in that code fragment: you're trashing the variable that holds the original lines. I highly recommend that you put the results of split into a different variable.
    foreach my $line ( @file ) { my @fields = split(/\s+/, $line); print "$fields[2]\n"; }
    avoids future problems.